I\'m aware that map is not prepared to be sorted. It\'s heavily optimized for fast and random key access and actually doesn\'t support std::sort.
My cur
If you iterate using the map iterator, you will get the items sorted on key as it internally uses balanced binary tree to store the values. So you could just extract the 10 values from it using the iterators. Is that what you want or you want to do something else? Please clarify.
EDIT: Instead of using the vector and sorting, you can directly use set and pass the comparison function. Then you can extract the top 10 elements. This is my test code:
typedef std::pair MyPair;
struct MyTestCompare
{
bool operator()(const MyPair& firstPair, const MyPair& secondPair) const
{
return firstPair.second < secondPair.second;
}
};
int main()
{
std::map m;
m[std::string("1")] = 10;
m[std::string("2")] = 40;
m[std::string("3")] = 30;
m[std::string("4")] = 20;
std::set s;
std::map::iterator iter = m.begin();
std::map::iterator endIter = m.end();
for(; iter != endIter; ++iter)
{
s.insert(*iter);
}
}