c++algorithmvectoriteratorc++20

Iterate forwards or backwards depending on order of iterators


I have an std::vector with entries, and two entries a and b that are guaranteed to be in that vector. I'm using std::find to get iterators aIt and bIt in the vector for a and b. But I don't know which of a and b comes first in the vector. Now I want to do something with all entries from a to b, for which I need to iterate from a to b, regardless of the order of these two. How can that be done ?

The conventional iterator comparison won't work if a comes after b in the vector:


std::vector<int> vec = {1, 2, 3, 4, 5};
int a = 5;
int b = 2;
auto aIt = std::find(vec.begin(), vec.end(), a);
auto bIt = std::find(vec.begin(), vec.end(), b);
for (; aIt != bIt; aIt++) {
  std::cout << *aIt << std::endl;
}

Output:

5
0
1041
0
825494064
909128761
2609
0
0
0
0
0
[...]
0
0
0
0
Segmentation fault (core dumped)

Solution

  • Because you are using a std::vector, you can just compare aIt and bIt and swap them if they are out of order.

    if (aIt > bIt)
      std::swap(aIt, bIt);
    for (; aIt != bIt; aIt++) {
      std::cout << *aIt << std::endl;