gpt4 book ai didi

c++ - 如何打印集合中的所有元素?

转载 作者:行者123 更新时间:2023-12-02 10:06:50 27 4
gpt4 key购买 nike

我很难打印出集合中的元素。

std::set<triple, Compare> edges;
for (int i = 0; i < n; i++)
for (std::list<std::pair<int, int>>::iterator j = graph[i].begin(); j != graph[i].end(); j++)
edges.insert(makeTriple((*j).second, i, (*j).first));

for (std::set<triple, Compare>::iterator j = edges.begin(); j != edges.end(); j++)
printf("%d and %d\n\n", (*j).first + 1, (*j).second + 1);

仅打印7个元素(共13个)。
比较功能如下所示:
bool operator()(const triple &a, const triple &b) const
{
if (a.distance == b.distance && a.first == b.first)
return (a.second < b.second);
if (a.distance == b.distance && a.second == b.second)
return (a.first < b.first);
return (a.distance < b.distance);
}

最佳答案

您的Compare函数不满足要求

The return value of the function call operation applied to an object of a type satisfying Compare, when contextually converted to bool, yields true if the first argument of the call appears before the second in the strict weak ordering relation induced by this type, and false otherwise.



最明显的解决办法是:
bool operator()(const triple &a, const triple &b) const {
if (a.distance == b.distance) {
if(a.first == b.first) return a.second < b.second;
else return a.first < b.first;
} else return a.distance < b.distance;
}

但是,这可以通过使用 <tuple>中的 std::tie更简单地完成:
bool operator()(const triple &a, const triple &b) const {
return
std::tie(a.distance, a.first, a.second) < std::tie(b.distance, b.first, b.second);
}

Demo

关于c++ - 如何打印集合中的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812073/

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