rttrorg / rttr

C++ Reflection Library
https://www.rttr.org
MIT License
3.17k stars 439 forks source link

variant_associative_view::find should return non-const iterator #240

Open moggabor opened 5 years ago

moggabor commented 5 years ago

Hi,

I'm trying to modify the data returned by variant_associative_view::find but I can't because find only returns a const_iterator. Example:

std::string key = "dataset1";
std::unordered_map<std::string, std::vector<int>> lookup;
lookup[key].assign(100000, 0); // some large dataset
rttr::variant lookupVar(std::ref(lookup));

auto lookupView = lookupVar.create_associative_view();
auto constIt = lookupView.find(key); // returns const_iterator :(
auto dataVar = constIt.get_value();
std::cout << dataVar.get_type().get_name();
// the vector is now const because of const_iterator:
// classstd::reference_wrapper<classstd::vector<int,classstd::allocator<int>>const >
auto dataView = dataVar.create_sequential_view();
auto sizeBefore = dataView.get_size(); // 100000
dataView.erase(dataView.begin()); // fails because vector is const
auto sizeAfter = dataView.get_size(); // still 100000
assert(sizeAfter < sizeBefore);

I don't want to create a copy of the data just to modify a small part of it.

This problem could be solved if variant_associative_view had non-const iterator and the respective overloads:

iterator variant_associative_view::find(argument key)
const_iterator variant_associative_view::find(argument key) const

I don't see any reason why variant_associative_view couldn't have non-const iterators. Maybe there could be a conceptual issue weather a view should be able to modify its underlying data. But since variant_associative_view already has methods like insert and erase, why couldn't it have non-const iterators as well? Would you be interested in a pull request which would implement non-const iterators?

Or is there a better way to solve my problem?

Thanks