gpt4 book ai didi

c++ - 在 C++11 的 std::set 中查找元素

转载 作者:太空宇宙 更新时间:2023-11-04 16:05:54 25 4
gpt4 key购买 nike

如果将对象插入到 std::set 中,关键是什么?对于下面的示例,我将类 Classcomp 的对象插入到 std::set 中。但是,我想查找 std::set 中是否存在具有特定“id = 1”的 Classcomp 对象?

#include <iostream>
#include <set>

struct Classcomp {
int val = 0;
int id = 0; ///ID for the object
bool operator() (const Classcomp& lhs, const Classcomp& rhs) const
{return lhs.val<rhs.val;}
};

int main ()
{

Classcomp c1,c2,c3,c4;
c1.val = 92;c1.id = 2;
c2.val = 94;c2.id = 3;
c3.val = 10;c3.id = 1;

std::set<Classcomp,Classcomp> fifth; // class as Compare

fifth.insert(c1);fifth.insert(c2);fifth.insert(c3);

for (auto x: fifth) {std::cout << x.id << " " << x.val << std::endl;}

if (fifth.find()) {std::cout << "Got it";} //What should I pass as arguments to fifth.find()?

return 0;
}

最佳答案

集合与 map 的不同之处在于集合内对象的 是它们的。如果您需要将键与值分开,则需要一个键值容器,例如 std::mapstd::unordered_map

澄清我不是在谈论简单地遍历集合中的所有对象并检查每个对象是否具有指定键的选项 - 这可以使用 std::find 轻松完成。如果那是您想要的,请说明。

关于c++ - 在 C++11 的 std::set 中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35585171/

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