0

According to the documentation, hashed index iterators remains valid when new elements are inserted into a multi_index. However when I attempted the following approach

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

the range.first/range.second seem to become invalid: even though std::distance(range.first, range.second) == 1, the for loop actually gets executed twice. Am I somehow not using it correctly? Thanks!

Joaquín M López Muñoz
  • 5,243
  • 1
  • 15
  • 20
Niko
  • 257
  • 1
  • 8
  • I suspect that your end iterator is being updated when you add new things to `myMultiIndex`. It's not clear why you'd be adding arguments in a loop like this. Perhaps instead you can measure the `distance` and loop for that instead, so you get `auto size = std::distance(range.first, range.second);`, then `for (size_t index = 0; index < size; ++index)` and add your arguments that way? This is all just speculation which is why I haven't answered per se. – Tas Aug 22 '18 at 01:18
  • @Tas sorry for the confusion,I am actually trying to duplicate the elements in the range with some parameters updated (something like emplace(iter->oldParam, newParam)). Maybe there is a better way to achieve this? – Niko Aug 22 '18 at 02:55

1 Answers1

1

When c++ libraries specify that iterators aren't invalidated by an operation it means that the iterators still point to the same element. For example in the following code:

std::list< int > l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
auto first = l.begin();
auto last = std::find(l.begin(), l.end(), 3);
std::cout << *first << std::endl;
std::cout << *last << std::endl;

1, 3 and 2 are printed. If we now insert some elements:

l.insert(last, 4);
l.insert(last, 5);
std::cout << *first << "\n";
std::cout << *last << "\n";
std::cout << std::distance(first, last) << "\n";

first and last are still valid and point to the same elements but the distance is now 4 so they point to a different range.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60