gpt4 book ai didi

c++ - 指定具有 3 个组件的 STL 映射键

转载 作者:行者123 更新时间:2023-11-30 01:55:32 24 4
gpt4 key购买 nike

我是 STL 的新手。如果这个问题很幼稚,请原谅我。

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

typedef pair <int, int> KeyPair;

我的 map 如下图

typedef map <KeyPair, uint32> NvInfoMap;

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

哪种方法最简单?

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

请注意,我在受限环境中,boost 库不可用。

感谢您的宝贵时间。

最佳答案

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

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

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

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

有一个允许它被用作 key 的命令

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++ - 指定具有 3 个组件的 STL 映射键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20680959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com