繁体   English   中英

C ++ std :: map和std :: pair <int, int> 作为关键

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

我有以下C ++代码:

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

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

现在,我在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
    }
}

我实际上想做的是通过交换另一对元素来形成一个对,例如,我在MyMap中有一个密钥对(12,16),还有另一个密钥对(16,12); 这两个密钥存在于MyMap中,我肯定知道。 但是当我应用上述技术MyMap时,不返回与交换的键相对应的值,我猜测MyMap.find(p)与Key的指针匹配; 但是有一种方法可以强制MyMap.find(p)匹配Key(对)中的对应值,而不是匹配Key(对)中的指针吗? 还是我在这里做错了什么?

您的代码中有一些不精确的地方,例如,您的MyStruct没有复制构造函数,但是包含数组,for循环中的itr->first() ,而first没有调用运算符,等等。 以下代码可以满足您的要求:

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

输出:

12 16 - 3 4
16 12 - 1 2

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM