简体   繁体   English

翻转地图键值对

[英]Flip map key-value pair

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
#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;
  }
}

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;
for (auto i=normal.begin(); i!=normal.end(); ++i)
    flipped[i->second] = i->first;

如果您想要在两个方向上查找,那么您可以使用Boost.bimap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法从地图上获取特定的键值对? - Is there a way to get a specific key-value pair from the map? 如何在地图中将STL未排序键值作为对使用 - How to use STL unsorted key-value as pair in map 指针只是键值对吗? - Is a pointer just a key-value pair? 不知道映射中是否存在键时,如何从映射中修改键值对的值? - How to modify the value of a key-value Pair from a map while I do not know whether the key is exist in the map? 无法从分离的线程访问C ++ unordered_map中的键/值对 - Cannot access key-value pair in a C++ unordered_map from a detached thread 使用键值对为零的 k 个存储桶初始化 c++14 unordered_map - Initialize c++14 unordered_map with k buckets with key-value pair of zero 如果在std :: map中操作不存在的键/值对,会发生什么? - What happens if one manipulates non-exist key-value pair in a std::map? 你能在亚线性时间内从 std::map 得到一个均匀随机的键值对吗? - Can you get a uniformly-random key-value pair from an std::map in sub-linear time? C++ 更新unordered_map中的值,其中键值对的数据类型为int-unordered_set - C++ Updating values in a unordered_map, where the data type of key-value pair is int-unordered_set 最快的预打包键值对搜索 - Fastest pre-packaged key-value pair search
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM