在 C++11 中的 std::set 中找到该元素

Find the element in a std::set in C++11

本文关键字:元素 set C++11 中的 std      更新时间:2023-10-16

如果将对象插入 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::mapstd::unordered_map

澄清我不是在谈论简单地迭代集合中的所有对象并检查每个对象是否具有指定键的选项 - 这很容易通过 std::find 完成。如果这是您想要的,请澄清。

由于您的类是按字段val排序的,因此您有以下选项:

  • 遍历所有元素,并通过std::findstd::find_if查找具有特定 id 的元素
  • 创建另一个容器并按 id 排序(可能使用 std::share_ptr 以避免重复
  • 使用boost::multiindex并按valid创建索引