I have an int vector and a mapping that contains some iterators pointing to the vector as values. I need to remove the keys from the map and the vector element that the value points to. My code looks briefly:
using RenderData = int;
using Element = std::string;
struct Ref {
std::vector<RenderData>::iterator ref;
std::function<int()> update;
bool should_remove;
};
int main() {
std::vector<RenderData> ints{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::unordered_map<Element, Ref> elements;
}
I implemented a function erase_if
that looked like this .
So my initial code looked like this:
erase_if(elements, [&](auto&& element) {
if (element.second.should_remove) {
ints.erase(element.second.ref);
return true;
}
return false;
});
That obviously didn't work. The erasing element causes another iterator to point to the wrong object, and in some cases to the anchor. So I tried this:
std::vector<std::vector<RenderData>::iterator> to_remove;
erase_if(elements, [&](auto&& element) {
if (element.second.should_remove) {
to_remove.emplace_back(element.second.ref);
return true;
}
return false;
});
std::sort(to_remove.begin(), to_remove.end(), std::greater<>{});
for (auto&& it : to_remove) {
ints.erase(it);
}
And again, I sometimes erased the wrong elements.
Given that iterators stored on a map can you remove elements pointed to by iterators from a vector?
Update:
, , . , , .