c++ - 用于映射一对一关系的 STL 类型?

标签 c++ c++11 stl containers bimap

在考虑我的代码关于一对一关系的设计决策时,我开始考虑是否应该使用 std::vector<std::pair<T1, T2>>而不是 std::map<T1, T2> , 并自己实现 A 到 B 和 B 到 A 两个方法。

我不能使用 boost,所以我找到的这个问题的答案 ( One-to-one relation in STL terms ) 不太合适。

是否有一些 STL 等价物可以完成这项工作?或者你认为 vector 是个坏主意?结构 ( < 10) 中不会有很多条目,但会有很多访问权限。

最佳答案

试试这个:

#include <string>
#include <map>

template <typename MapA2B, typename MapB2A = std::map<MapA2B::mapped_type, MapA2B::key_type> >
MapB2A CreateInverseMap(const MapA2B& map)
{
    MapB2A ret;
    for (const MapA2B::value_type& value : map)
        ret[value.second] = value.first;
    return ret;
}

void Test()
{
    typedef std::map<int, std::string> A2B;
    A2B a2b =
    {
        { 1, "D" },
        { 2, "AA" },
        { 3, "CCC" },
    };
    typedef std::map<std::string, int> B2A;
    B2A b2a = CreateInverseMap(a2b);

    std::string b = a2b[2]; // b = "AA";
    int a = b2a["CCC"]; // a = 3;
}

关于c++ - 用于映射一对一关系的 STL 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54398336/

相关文章:

c++ - 级联流插入运算符不起作用

c++ - 在 C++ 中对大量元素进行分组的最快方法

c++ - undefined reference ;类公共(public)函数在链接时不可访问

c++ - Gtkmm:将 RefPtr 与保存在 std::vector 中的小部件一起使用

c++ - std::allocator 释放部分内存

c++ - 如何将 std::unordered_multimap<uint, T> 转储到 std::vector<T>?

c++ - 在 const 成员函数中使用 bind1st

C++ A星实现--判断节点是否已经在未清项优先队列中

c++ - 模板函数重载

c++ - 当我们迭代它时更改 HashMap 的行为是否已定义?