Re: std::map: best way to get biggest key?
Paavo Helde wrote:
No failing, rbegin() always (if the map is not empty) returns the last key
- in the sorting order of the map, that is. This is the largest value,
std::map does not know or care about any other sorting criterias you might
want to use elsewhere in your code.
The std::map container is sorted, according to the key comparison function
used.
The rbegin() method returns an iterator pointing to the last element of the
range, but that range is sorted according to the key comparison function
used in a std::map.
So, as it is possible to pass any other key comparison function in a
std::map definition, rbegin() may or may not point to the element with the
biggest key.
To demonstrate:
<example>
rui@Kubuntu:tmp$ cat main.c++
#include <map>
#include <functional>
#include <iostream>
int main(void)
{
using namespace std;
map<int, int> lesser;
map<int, int, std::greater<int> > greater;
for(int i = 0; i < 10; i++)
{
lesser[i] = 2*i;
greater[i] = 2*i;
}
cout << "lesser:\n";
for(auto i: lesser)
{
cout << "\t(" << i.first << "," << i.second << ")";
}
cout << endl;
cout << "last element: " << "(" << lesser.rbegin()->first << "," <<
lesser.rbegin()->second << ")" << endl;
cout << "greater:\n";
for(auto i: greater)
{
cout << "\t(" << i.first << "," << i.second << ")";
}
cout << endl;
cout << "last element: " << "(" << greater.rbegin()->first << "," <<
greater.rbegin()->second << ")" << endl;
return 0;
}
rui@Kubuntu:tmp$ ./main
lesser:
(0,0) (1,2) (2,4) (3,6) (4,8) (5,10) (6,12) (7,14)
(8,16) (9,18)
last element: (9,18)
greater:
(9,18) (8,16) (7,14) (6,12) (5,10) (4,8) (3,6) (2,4)
(1,2) (0,0)
last element: (0,0)
</example>
Rui Maciel