1

I am trying to do something like this:

auto& myIndex = myMultiIndex.get<0>();
auto range = myIndex.equal_range(x);
for (auto iter = range.first; iter != range.second; ++iter) {
    if (somePredicate) myIndex.erase(iter);
}

Of course this does not work because the iterator becomes invalid once we erase an element from the container. Also std::remove_if doesn't work since it modifies and overwrites elements in the container which will mess up the other indices. What is the recommended way of doing something like this?

Thanks!

Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20
Niko
  • 257
  • 1
  • 8

1 Answers1

0
for (auto iter = range.first; iter != range.second;) {
    if (somePredicate) iter = myIndex.erase(iter);
    else ++iter;
}
Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20
  • This will still leave the iterator invalid if `somePredicate`, and so does not solve op's problem. – kabanus Aug 15 '18 at 11:24
  • The solution suggested in the other question you linked to checks iter != myIndex.end() in the for loop, which works because the end() keeps updating as we erase elements. However in my case I am filtering on a range rather than the entire multi_index, so we don't have that benefit. – Niko Aug 16 '18 at 05:15
  • Boost.MultiIndex iterators are always _stable_, which means the code I'm suggesting is perfectly safe --`range.second` remains valid throughout the loop. – Joaquín M López Muñoz Aug 16 '18 at 07:40