【问题标题】:Specifying STL Map key with 3 components使用 3 个组件指定 STL Map 键
【发布时间】:2013-12-19 11:48:03
【问题描述】:

我对 STL 还很陌生。如果这个问题很幼稚,请原谅我。

我有一对像这样用作地图的键。

typedef pair <int, int> KeyPair;

我的地图如下图

typedef map <KeyPair, uint32> NvInfoMap;

现在我想在地图的 Key 部分引入一个新整数。

最简单的方法是什么?

我是否必须制作另一对将现有对作为其后半部分?

请注意,我处于无法使用 boost 库的受限环境中。

感谢您的宝贵时间。

【问题讨论】:

  • 考虑使用std::tuple 而不是一对。 typedef tuple<int, int, int> KeyType;
  • @SeanCline :不支持元组。决定使用嵌套对。

标签: c++ stl


【解决方案1】:

如果你的限制允许 C++11,那么

typedef std::tuple<int, int, int> KeyTriple;

否则,您可以定义自己的类型

struct KeyTriple {
    int a;
    int b;
    int c;
};

带有一个允许它用作键的顺序

bool operator<(KeyTriple const & lhs, KeyTriple const & rhs) {
    if (lhs.a < rhs.a) return true;
    if (rhs.a < lhs.a) return false;
    if (lhs.b < rhs.b) return true;
    if (rhs.b < lhs.b) return false;
    if (lhs.c < rhs.c) return true;
    return false;

    // Alternatively, if you can use C++11 but don't want a tuple for a key
    return std::tie(lhs.a, lhs.b, lhs.c) < std::tie(rhs.a, rhs.b, rhs.c);
}

或者,正如您所建议的,您可以使用嵌套对

typedef std::pair<int, std::pair<int, int>>;

优点是它为您定义了必要的比较运算符,但缺点是创建一个并访问其元素有点麻烦。

【讨论】:

  • 谢谢。老实说,我不知道我是否可以使用 C++ 11。我现在会检查一下。这适用于基于 MIPS 的嵌入式目标。
  • operator&lt; 太长了。可以写成return tie(lhs.a, lhs.b, lhs.c) &lt; tie(rhs.a, rhs.b, rhs.c);
  • @SeanCline:这需要 C++11,在这种情况下,您可能还是会使用 tuple。 (我想你可以嵌入一个数组而不是三个变量,并使用lexicographical_compare,如果你想避免编写这个有点容易出错的代码)。
  • @MikeSeymour,支持TR1 的编译器非常普遍。我忘记了它是新标准。
猜你喜欢
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多