std::map with std::pair keys where pair elements has no order importance
c++, stl
Solution
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;
Problem
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? Two ideas come to my mind. 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. 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) Thanks.