C++ std::map items in descending order of keys -
how cal use std::map container key value in descending order.
as example, if insert following items:
[2 , 5] [1 , 34] [3 , 67]
they ordered in map like:
position 0: [1, 34] position 1: [2, 5] position 2: [3, 67]
i can iterate through map reversely, suppose next time inserting [-1 , 60]. placed @ first position?
use custom comparator when default order doesn't you.
pass third template parameter ( that's defaulted std::less<keytype>
).
in case, can use std::greater
:
std::map<int, int, std::greater<int> > m;
example code:
#include <map> #include <iostream> int main() { std::map<int, int, std::greater<int>> m { {-1, 77}, {0, 42}, {1, 84} }; (const auto& p : m) std::cout << '[' << p.first << ',' << p.second << "]\n"; }
resulting output:
[1,84] [0,77] [-1,42]
Comments
Post a Comment