Map with key是c++中多个值的组合

map with key which is combination of multiple values in c++

本文关键字:组合 with key c++ Map      更新时间:2023-10-16

我想要一个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_variable.find(key_type("keyStrning3", 1, "keyString2")).

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

您可以使用boost::variant(或std::variant c++ 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;
}