【问题标题】:map with key which is combination of multiple values in c++带有键的映射,它是 C++ 中多个值的组合
【发布时间】:2016-09-19 12:46:13
【问题描述】:

我想要一个 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 是否有任何方便的解决方案。

【问题讨论】:

  • 你可以有一个以这些成员为key的类。
  • 所以你希望键是一个结构,或者可能是一个元组?对于std::map,您真正需要做的就是实现比较运算符。
  • 第二个和第三个键可以是字符串还是整数?所以key_type("ss", 1, "333") 是一个有效的密钥,key_type("ss", "aa", 1) 也应该是有效的。
  • 是的,@giuseppe-pes、key_type("ss", 1, "333")key_type("ss", "aa", 1) 都是有效密钥
  • 然后std::variant 是要走的路..

标签: c++ boost stl set


【解决方案1】:

您可以使用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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    相关资源
    最近更新 更多