spiritwolfform
spiritwolfform

Reputation: 2293

Optimal mapping for pairs of string

I have lots of string pairs and I'm looking for a good way to map strings within these pairs to each other.
Say if i have str1 and str2 pair, i need to return str2 for str1 and str1 for str2.
I know i can use a map for this

map<string, string>

But if i simply use a std::map for this, i will need to store each string twice as a key and as a value.
Which is the optimal solution to avoid duplication? Is there a special container optimized for this?

Upvotes: 0

Views: 87

Answers (1)

ForEveR
ForEveR

Reputation: 55887

Use boost::bidirectional_map. http://www.boost.org/doc/libs/1_52_0/libs/bimap/doc/html/index.html

Simple example

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

int main()
{
   namespace bi = boost::bimaps;
   typedef bi::bimap<std::string, std::string> bimap;

   bimap map;
   map.insert(bimap::value_type("1", "2"));
   std::cout << map.left.at("1") << std::endl;
   std::cout << map.right.at("2") << std::endl;
}

http://liveworkspace.org/code/jitNY$0

Upvotes: 2

Related Questions