12

I have a map. I want to flip the key-value so that it not becomes map. So basically the value of the first map becomes the key of the second map. How do i do this?

Example map:

1 - 1.0
2 - 2.0

After flip

1.0 - 1
2.0 - 2
Richard
  • 5,840
  • 36
  • 123
  • 208

4 Answers4

11

The most straightforward way (that I know of) is to create a new map with the types flipped, and iterate the old one and add each key-value pair in reverse.

For example,

map<int, float> if_map;

// insert some items into if_map
if_map[1] = 43.11;
if_map[44] = -13421.438;

map<float, int> reversed;

for (map<int, float>::iterator i = if_map.begin(); i != if_map.end(); ++i)
    reversed[i->second] = i->first;
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • 5
    This answer works if the original mapping is one-to-one. If not, this code will lead to some information loss. To solve this issue, either use [Boost.bimap](http://www.boost.org/doc/libs/1_42_0/libs/bimap/doc/html/index.html) as [@Asha](http://stackoverflow.com/users/392315/asha) [suggested](http://stackoverflow.com/a/8321400/377657), or return the result as a `vector`. – rwong Mar 18 '13 at 17:56
  • 8
    Or, store the resulting flipped map in an std::multimap. – strickli Sep 26 '13 at 19:13
10
#include<iostream>
#include<map>
#include<algorithm>

using namespace std;

template<typename A, typename B>
pair<B,A> flip_pair(const pair<A,B> &p)
{
    return pair<B,A>(p.second, p.first);
}

template<typename A, typename B>
map<B,A> flip_map(const map<A,B> &src)
{
    map<B,A> dst;
    transform(src.begin(), src.end(), inserter(dst, dst.begin()), 
                   flip_pair<A,B>);
    return dst;
}

int main(void)
{
  std::map<char, int> src;

  src['a'] = 10;
  src['b'] = 20;
  src['c'] = 160;
  src['d'] = 110;
  src['e'] = 0;

  std::map<int, char> dst = flip_map(src);

  map<int, char>::iterator it;
  for(it=dst.begin(); it!=dst.end(); it++) {
    cout << it->first << " : " << it->second << endl;
  }
}
Krishnachandra Sharma
  • 1,332
  • 2
  • 20
  • 42
5
for (auto i=normal.begin(); i!=normal.end(); ++i)
    flipped[i->second] = i->first;
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • The resulting flipped map should be an std::multimap, or duplicate values will overwrite keys, resulting in lost data (which may be what is desired?) – strickli Sep 26 '13 at 19:15
3

If you want lookup in both directions then you can use Boost.bimap

Asha
  • 11,002
  • 6
  • 44
  • 66