user963167
user963167

Reputation: 21

C++ std::map and std::pair<int, int> as Key

I've the following C++ code:

struct MyStruct
{
    int a[2];
    int b[2];
};

std::map<std::pair<int, int> , MyStruct*> MyMap;

Now I run this loop on MyMap:

for(std::map<std::pair<int, int> , MyStruct*>::iterator itr = MyMap.begin(); itr != MyMap.end(); ++itr)
{
    std::pair<int, int> p (itr->first().second, itr->first().first);
    auto i = MyMap.find(p);
    if(i != MyMap.end())
    {
        //do something
    }
}

What I'm actually trying to do is forming a pair by swapping the elements of another pair , so for example I have a key pair(12,16) in MyMap and also another key pair(16,12); these two key exists in MyMap and I know for sure. But when I apply the above technique MyMap don't return the value corresponding to the swapped key, what I'm guessing that MyMap.find(p) is matching the pointer of Key; but is there a way so that I can force MyMap.find(p) to match the corresponding value in Key (pair) instead of matching the pointers in Key (pair) ? Or is there anything I'm doing wrong here ?

Upvotes: 2

Views: 3950

Answers (1)

awesoon
awesoon

Reputation: 33661

You have some imprecisions in your code, say, your MyStruct does not have a copy constructor, but contains arrays, itr->first() in your for loop, while first doesn't have a call operator, and others. The following code does what you want:

#include <array>
#include <map>
#include <utility>
#include <memory>
#include <stdexcept>
#include <iostream>

struct MyStruct
{
    std::array<int, 2> a;
    std::array<int, 2> b;
};

template <class T, class U>
std::pair<U, T> get_reversed_pair(const std::pair<T, U>& p)
{
    return std::make_pair(p.second, p.first);
}

int main()
{
    std::map<std::pair<int, int>, std::shared_ptr<MyStruct>> m
    {
        {
            {12, 16},
            std::make_shared<MyStruct>()
        },
        {
            {16, 12},
            std::make_shared<MyStruct>()
        }
    };

    std::size_t count = 1;

    for(const auto& p: m)
    {
        try
        {
            auto f = m.at(get_reversed_pair(p.first));
            f -> a.at(0) = count++;
            f -> b.at(0) = count++;
        }
        catch(std::out_of_range& e)
        {

        }
    }

    for(const auto& p: m)
    {
        std::cout << p.first.first << ' ' << p.first.second << " - ";
        std::cout << p.second -> a.at(0) << ' ' << p.second -> b.at(0) << std::endl;
    }

    return 0;
}

Output:

12 16 - 3 4
16 12 - 1 2

Upvotes: 1

Related Questions