Can STL or Boost help sort a map by value?

Viewed 260

The word "sorting" in the title may be misleading here. I'm looking for this behaviour:

{ 1: 100,               { 1: 1,
  3: 10,        =>        3: 10,
  5: 1000,                5: 100,
  9: 1 }                  9: 1000 }

That is, reassign the values to existing keys in ascending order.

This would not be hard to do with a temporary:

using K = int;
using V = int;
std::map<K, V> myMap{ {1, 100}, {3, 10}, {5, 1000}, {9, 1} };
std::vector<V> tempVec; // insert map values into vector
std::transform(myMap.begin(), myMap.end(), std::back_inserter(tempVec),
               [](auto const& mapPair) { return mapPair.second; });
std::sort(tempVec.begin(), tempVec.end());
size_t i = 0;
for (auto& mapPair : myMap) {
    mapPair.second = tempVec[i++];
}

Can this be simplified or even better, be done in place?

2 Answers
Related