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:
<code>
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++) {
doSomething(*aIt);
}
</code>
<code>
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++) {
doSomething(*aIt);
}
</code>
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++) {
doSomething(*aIt);
}