Flip map key-value pair

前端 未结 4 1063
后悔当初
后悔当初 2021-01-11 17:10

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?

E

4条回答
  •  不要未来只要你来
    2021-01-11 17:24

    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 if_map;
    
    // insert some items into if_map
    if_map[1] = 43.11;
    if_map[44] = -13421.438;
    
    map reversed;
    
    for (map::iterator i = if_map.begin(); i != if_map.end(); ++i)
        reversed[i->second] = i->first;
    

提交回复
热议问题