Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading