2016-09-19 118 views
1

我想要一个C++中的映射,其中的键是多个值的组合。我可以同时使用stl和boost。使用C++中的多个值组合的键映射的映射

键值可以是字符串/整数类似下面

typedef value_type int; 
typedef key(string, template(string,int), template(string,int)) key_type; 
typedef map(key_type, value_type) map_type; 

map_type map_variable; 
map_variable.insert(key_type("keyStrning1", 1, "keyString2"), 4); 
map_variable.insert(key_type("keyStrning3", 1, "keyString2"), 5); 

现在,这个地图将包含两个条目,我应该能够找到它象下面这样:

map_variable.find(key_type("keyStrning3", 1, "keyString2")). 

我可以使用嵌套地图,但我想知道是否有任何方便的解决方案,使用boost或C++ stl。

+0

你可以有一个以这些成员为关键的类。 – Hayt

+1

所以你想要的钥匙是一个结构,或可能是一个tupple?对于['std :: map'](http://en.cppreference.com/w/cpp/container/map),你真正需要做的就是实现比较运算符。 –

+0

第二个和第三个键可以是一个字符串还是一个整数?所以'key_type(“ss”,1,“333”)'是一个有效的键,'key_type(“ss”,“aa”,1)'也应该是有效的。 –

回答

3

您可以使用boost::variant(或std::variantC++ 17将准备好)。

#include <tuple> 
#include <map> 
#include <utility> 
#include <boost/variant/variant.hpp> 

typedef int ValueType; 
typedef boost::variant<std::string, int> StrOrInt; 
typedef std::tuple<std::string, StrOrInt, StrOrInt> KeyType; 
typedef std::map<KeyType, ValueType> MapType; 

int main(int argc, char *argv[]) { 
    MapType amap; 
    amap.insert(std::make_pair(
       std::make_tuple("string1", "string2", 3), <--- key 
       4)); // <--- value 

    auto finder = amap.find(std::make_tuple("string1", "string2", 3)); 

    std::cout << finder->second << '\n'; // <--- prints 4 

    return 0; 
}