在 C++11 中的 std::set 中找到该元素
Find the element in a std::set in C++11
如果将对象插入 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;
}
集合与映射的不同之处在于,集合内对象的值就是它们的键。如果需要将键与值分开,则需要键值容器,例如 std::map
或 std::unordered_map
。
澄清我不是在谈论简单地迭代集合中的所有对象并检查每个对象是否具有指定键的选项 - 这很容易通过 std::find
完成。如果这是您想要的,请澄清。
由于您的类是按字段val
排序的,因此您有以下选项:
- 遍历所有元素,并通过
std::find
或std::find_if
查找具有特定 id 的元素 - 创建另一个容器并按 id 排序(可能使用 std::share_ptr 以避免重复 )
- 使用
boost::multiindex
并按val
和id
创建索引
相关文章:
- 对于set上的循环-获取next元素迭代器
- set::find 查找不存在的元素
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 如何从 std::set 绘制 n 个元素的样本
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 如何在对数时间内访问 c++ std::set 中的第 k 个元素?
- 语言的哪一部分禁止更改 std::set 的元素
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 在 std::set 中查找 std::vector 的元素
- 创建 std::set 只复制一个元素,如何解决这个问题?
- 为什么 std::set 遍历所有元素的速度较慢?
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 直接访问 STL "set"元素
- 新元素将在std :: set中插入哪里
- std :: set and std :: unordered_set构造元素与emplace()如何
- 通过与不同类型的值进行自定义比较来查找 std::set 的元素
- 删除 std::set<Node *> 中的元素的正确方法
- 如何使用反向迭代器从“std::set”中删除元素
- 给定一个 std::set::iterator,获取一个指向下一个元素的迭代器
- 无法将 std::set 中的元素迭代器插入到 std::list