Map that can search in both values and keys about

2019-09-18 00:26发布

问题:

I am about to have up to 50 entries in a <unsigned long, const char*> map. The reason for this is that protocol I'm using references string names by numbers after inital handshake - I assume similar map as mine must exist on the server.

What I wanted was a map that can be searched for both key and value (both are guaranteed to be unique and bound together) with about the same code complexity and performance cost. One idea was:

symethric_map<unsigned long, const char*> map;
map[165]="NODE_A";
std::cout<<map->inverse["NODE_A"]<<std::endl; // Should print 165

The idea in this code is that symethric_map<T,N>::inverse is an object that can treat map keys as values and vice versa. Of course, map with simple searchValue method would solve that problem too.

I am asking for this because I will be constantly resolving number to strings and vice versa and without any reliable number generating system, the only way to do that is to remember all the relations. std::vector could be used if the numbers were ordinal, which will not allways be the case. I am willing to use any boost feature as well as C++11 tricks.

回答1:

Simples use-case:

Live On Coliru

#include <boost/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <iostream>

namespace bm = boost::bimaps;

using symethric_map = bm::bimap<bm::set_of<unsigned long>, bm::set_of<const char*, std::less<std::string> > >;

int main() {
    symethric_map map;
    map.left.insert({165, "NODE_A"});
    std::cout << map.right.at("NODE_A") << "\n";
}

Prints

165


标签: c++ boost