c++ - 映射键是 C++ 中多个值的组合

标签 c++ boost stl set

我想要一个 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/

相关文章:

c++ - 无法编译代码,因为它在 C++11 中已弃用

c++ - Python -> C++ 习语 : Storing lambda expressions in a map/container

用于 boost/c++11 的 C++ 包装器

c++ - 应该使用插入排序还是构造堆来 boost 性能?

C++ 运算符 << 调用::ostream 而不是 std::ostream

c++ - 列出 max_size 实现

C++ 断点被忽略/遗漏

c++ - 这些 valgrind/GNU 调试器错误消息是什么意思?

boost - 为什么我应该在 boost::asio 中使用自定义处理程序分配器 (custom_alloc_handler)?

c++ - 在 C++ 中增加大数字(近 100.000 位)