1

I have an STL map that has String keys and int values. I need to put the items into a new map with int keys and String values, such that the keys are sorted from lowest to greatest.

For example I have a map with these values(key, value):

"A", 5
"B", 2
"C", 8
"D", 4

I would like them to then be arranged in such a way that they look like this(key, value):

2, "B"
4, "D"
5, "A"
8, "C"

Where the value from the original map becomes the key, and the key becomes the value.

I know that I need to add the values from the original map to a new map, but I'm not sure how I would add them in a way that they're sorted from lowest to greatest.

Darren
  • 1,774
  • 4
  • 21
  • 32

3 Answers3

4

Something along these lines perhaps:

std::map<std::string, int> old_map = ...;  // initialized somehow
std::map<int, std::string> new_map;

std::transform(old_map.begin(), old_map.end(),
  std::inserter(new_map, new_map.end()),
  [](decltype(old_map)::iterator it) {
    return std::make_pair(it->second, it->first);
  }
);
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
2

For each pair in the original map, reverse the pair and insert into the other map. The sorting is automatic because std::map is sorted by key.

Also, if you might have multiple keys in the original map with the same data (for example both "A" and "E" have the data 5) then you need to be using std::multimap instead.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

For std:map, it is order by key default.

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

Please read the link:http://www.cplusplus.com/reference/map/map/

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <map>
using namespace std;

int main() {
    map<string, int> myMap;
    myMap["D"] = 4;
    myMap["C"] = 8;
    myMap["B"] = 2;
    myMap["A"] = 5;
    cout<<"before:"<<endl;
    for_each(myMap.begin(), myMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;});

    map<int, string> otherMap;
    cout<<"after:"<<endl;
    for_each(myMap.begin(), myMap.end(), [&otherMap](auto& element){otherMap[element.second] = element.first;});
    for_each(otherMap.begin(), otherMap.end(), [](auto& element){cout<<element.first<<" "<<element.second<<endl;});
    return 0;
}

Here is the code exmaple: the output is:

before:
A 5
B 2
C 8
D 4
after:
2 B
4 D
5 A
8 C

So you don't sort it by yourself.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67