Re: std::map: best way to get biggest key?
On Feb 12, 4:16 pm, Rui Maciel <rui.mac...@gmail.com> wrote:
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 mi=
ght
want to use elsewhere in your code.
The std::map container is sorted, according to the key comparison functio=
n
used.
The rbegin() method returns an iterator pointing to the last element of t=
he
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 th=
e
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.seco=
nd << ")";
}
cout << endl;
cout << "last element: " << "(" << lesser.rbegin()->first=
<< "," <<
lesser.rbegin()->second << ")" << endl;
cout << "greater:\n";
for(auto i: greater)
{
cout << "\t(" << i.first << "," << i.seco=
nd << ")";
}
cout << endl;
cout << "last element: " << "(" << greater.rbegin()->firs=
t << "," <<
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
map or set don't know anything about ordering your elements except the
comparison you give to them (or the default, std::less). map and set
are generic, and therefore don't know about numbers either.
I don't see why you expect them to know how elements should be
ordered, or that you might think they should be ordered.
Think about it this way: if your key wasn't a number or a string, how
do map or set even work? Something has to explain ordering to them.
And then, they both only know about __that__ particular ordering. They
aren't trying to guess that you are using std::greater and that there
is a "natural" "smaller" ordering they should ever use. For all they
know, you might pass in a comparison method where 42 is smaller than
anything else.