gpt4 book ai didi

c++ - 使用自定义 less 运算符实现迭代 std::map 会给出更少的元素

转载 作者:行者123 更新时间:2023-12-01 19:43:11 28 4
gpt4 key购买 nike

假设我有以下简单程序( http://cpp.sh/5sygh ):

#include <map>
#include <iostream>

using Key = std::pair<unsigned long, unsigned long long>;

struct KeyLess {
bool operator()(const Key& lhs, const Key& rhs) {
if (lhs.first < rhs.first) {
return true;
}

if (lhs.second < rhs.second) {
return true;
}

return false;
}
};

int main() {
std::map< Key , int, KeyLess> m;
m[Key{2, 169}] = 1;
m[Key{1, 255}] = 2;
m[Key{1, 391}] = 3;
m[Key{1, 475}] = 4;

std::cout << "Elements in map: " << m.size() << std::endl;
for(const auto &x: m) {
std::cout <<"Value: "<< x.second << std::endl;
}
}

输出仅包含 2 个项目,而不是 map 中的 4 个:

Elements in map: 4
Value: 2
Value: 1

我在这里想念什么?

最佳答案

您的 less 运算符应该是:

struct KeyLess {
bool operator()(const Key& lhs, const Key& rhs) {
if (lhs.first < rhs.first) {
return true;
}

if (lhs.first == rhs.first && lhs.second < rhs.second) {
return true;
}

return false;
}
};

当您将结构与多个元素进行比较时,将结构视为单词并将元素视为字符可能会有所帮助。

通过此修改,less 运算符按字典顺序工作,就像在对两个相同长度的单词进行排序时比较它们一样:当单词在当前位置具有相同字符时,您继续在下一个位置进行比较,并决定何时当前位置的字符不同。如果到达两个单词的末尾,则这两个单词相等。

关于c++ - 使用自定义 less 运算符实现迭代 std::map 会给出更少的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60734443/

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