-2

I have a map in c++ let say

mp =  
 [1:2,
  2:3,
  3:2]

in general map stores the data such that the keys are in sorted manner. is there any way to store data such that the values are in sorted i.e the new map should be mp_new =

 [2:1,
  3:2,
  2:3]

1 Answers1

0

Try using

std::unordered_map

from the header

<unordered_map>

Edit: I realize my answer did not fully answer your question.

This does what you want, although it is not a very efficient solution.

//Create new map
std::unordered_map<int, int> map;

map[1] = 2;
map[2] = 3;
map[3] = 1;

//Create vector to sort map
std::vector<std::pair<int,int>> tmp;

for (auto p : map)
{
    tmp.push_back(std::make_pair(p.second, p.first));
}

std::sort(tmp.begin(), tmp.end());

map.clear();

for (auto p : tmp)
{
    map.insert(std::make_pair(p.second, p.first));  
}

//Display new map values
for (auto a : map) std::cout << a.first << ':' << a.second << '\n';

Besides <unordered_map>this solution requires the following headers:

<algorithm>
<vector>
qwarten
  • 105
  • 2
  • 6
  • 1
    [Documentation](https://en.cppreference.com/w/cpp/container/unordered_map) for the lazy. – tadman Aug 11 '18 at 19:30
  • 3
    How this respond to the question? – max66 Aug 11 '18 at 19:32
  • I think he needs the map sorted by _values_, not by keys, not unsorted: _"such that the values are in sorted"_. – zdf Aug 11 '18 at 19:33
  • `unordered_map` does not guarantee the order of inserted elements. To which bucket an element is added depends on the hash of its key. So even if it works for some sets, it won't work for all sets. – zdf Aug 11 '18 at 21:40