std::map 与 std::pair 键,其中对元素没有顺序重要性 [英] std::map with std::pair keys where pair elements has no order importance

查看:40
本文介绍了std::map 与 std::pair 键,其中对元素没有顺序重要性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所说,我需要以这种方式使用 std::map.

As the question says, I need to use std::map in such way that.

std::map<std::pair<int, int>, int*> m;

int* a_ptr = new int;
*a_ptr = 15;
m[std::make_pair(1, 2)] = a_ptr;
std::cout << *m[std::make_pair(2, 1)] << std::endl; //should output 15

现在,在我的实际实现中,所有的键和值实际上都是指针.我应该如何解决这个问题?

Now, in my actual implementation all the keys and values are actually pointers. How should I approach this problem?

我想到了两个想法.

  1. 一个是我应该写一个函数,每次我使用 m[]访问或写入地图,我还应该 m.find() 检查其他配对组合并按此操作.

  1. One is I should write a function that every time I am using m[] to access or to write into map, I should also m.find() check the other pair combination and act according to that.

其他人正在使用带有自定义散列器的 std::unordered_mappair 的元素位置切换时,不知何故没有区别.(我不知道如何做到这一点,如果我乘以或添加两个指针的结果将不相等.如果是这样,需要一些帮助要走的路.)

Other is using std::unordered_map with a custom hasher that somehow makes no difference when pair's elements positions are switched. (I have no idea how to do this, if I multiply or add the two pointers the result won't be equal. Need some help if this is the way to go.)

如果你能想到更好的方法,我会很高兴听到的,否则我已经在第二个条款中说明了我需要帮助的地方.(我认为效率更高,第一个不好看)

If you can think a better method I will be glad to hear it, otherwise I have stated what I need help with in the second clause. (which I think is more efficient, first one does not look good)

谢谢.

推荐答案

您能否简单地确保这些对始终处于相同的顺序?使用辅助函数,例如:

Could you simply ensure the pairs are always in the same order? Use a helper function, like:

std::pair<int,int> my_make_pair(int a, int b) 
{
    if ( a < b ) return std::pair<int,int>(a,b);
    else return std::pair<int,int>(b,a);
}

并始终使用它来访问地图:

and always use it to access the map:

m[my_make_pair(1,2)] = a_ptr;
std::cout << m[my_make_pair(2, 1)] << std::endl;

这篇关于std::map 与 std::pair 键,其中对元素没有顺序重要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆