我想要一个 C++ 中的映射,其中它的键是多个值的组合。我也可以同时使用 STL 和 boost。
键值可以是字符串/整数,如下所示
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 将包含两个条目,我将能够像下面这样找到它:
map_variable.find(key_type("keyStrning3", 1, "keyString2")).
我可以使用嵌套映射,但我想知道使用 boost 或 c++ STL 是否有任何方便的解决方案。
最佳答案
您可以使用 boost::variant
(或在 C++17 准备就绪时使用 std::variant
)。
#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;
}
关于c++ - 映射键是 C++ 中多个值的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573562/