Reputation: 757
I have the following example program:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<int, int> a;
a[8] = 1;
a[5] = 1;
a[1] = 1;
a[2] = 1;
std::cout << a.begin()->first << std::endl;
std::cout << a.rbegin()->first << std::endl;
std::cout << (++a.rbegin())->first << std::endl;
std::cout << (--a.rbegin())->first << std::endl;
std::cout << (a.lower_bound(6))->first << std::endl;
}
When I execute it I get this output:
1
8
5
5
8
I have two questions. The first is why ++a.rbegin()
and --a.rbegin()
iterate in the same direction? Is the iterator returned from a.rbegin()
not a bidirectional iterator?
The second question is why does a.lower_bound(6)->first
return 8 instead of 5? Based on https://en.cppreference.com/w/cpp/container/map/lower_bound, it should return an iterator to the first element "not less than key". So I would have thought 5 would be returned since 8 > 6.
Upvotes: 0
Views: 5588
Reputation: 7374
--a.rbegin() is a UB.
lower_bound(val)
returns an iterator pointing to the first element in the range which does not compare less than val
. 5
is not "not less than 6
" so you get the iterator to 8
correctly
Upvotes: 2