Let's look at the following code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> exmpl = { 2, 3, 6, 9, 134, 1143, 2345 };
auto LessThan = [](const int a, const int b) -> bool { return a < b; };
auto GreaterThan = [](const int a, const int b) -> bool { return a > b; };
auto it_reverse_less_than = std::lower_bound(exmpl.rbegin(), exmpl.rend(), 8, LessThan);
auto it_reverse_greater_than = std::lower_bound(exmpl.rbegin(), exmpl.rend(), 8, GreaterThan);
auto it_forward_less_than = std::lower_bound(exmpl.begin(), exmpl.end(), 8, LessThan);
auto it_forward_greater_than = std::lower_bound(exmpl.begin(), exmpl.end(), 8, GreaterThan);
std::cout << *it_reverse_less_than << "\n";
std::cout << *it_reverse_greater_than << "\n";
std::cout << *it_forward_less_than << "\n";
std::cout << (it_forward_greater_than == exmpl.end());
return 0;
}
It gives the following output:
2345
6
9
1
I've checked the results using VC++ compiler as well as gcc via Ideone (see the link below) and they are the same.
I think it_reverse_greater_than
points to 1143
as it is the first element that the reverse iterator sees for which the compare function returns false
. I don't understand though why the GreaterThan
function doesn't return a match when used with forward iterators (it_forward_greater_than
points to end()
). Shouldn't it_forward_greater_than
point to 2
as it is the first element for which the compare function returns false
? Isn't it an analogical situation to it_reverse_greater_than
pointing to the last element, i.e. the first one that the reverse iterator sees?
Here is the code in Ideone:
https://ideone.com/0z55ss