2016-09-19 58 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; 
}