STL Type for mapping one-to-one relations?

400 Views Asked by At

when thinking about design decisions of my code regarding one-to-one relations I came to think about if I should use std::vector<std::pair<T1, T2>> instead of std::map<T1, T2>, and implement two methods A to B and B to A myself.

I can't use boost, so the answer to this question I found about it (One-to-one relation in STL terms) is not really fitting.

Is there some STL equivalent doing this job? Or do you think the vector is a bad idea? There won't be many entries in the struct ( < 10) but there will be a lot of access on it.

2

There are 2 best solutions below

1
GuangshengZuo On

I think in your case, you could try std::unordered_map<T1,T2> and std::unordered_map<T2,T1>. By using two unordered_map, you could do A2B and B2A both in O(1) time, which is faster than map or vector.

1
guest On

Try this:

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