簡體   English   中英

在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::mapstd::unordered_map

澄清我不是在談論簡單地迭代集合中的所有對象並檢查每個對象是否具有指定鍵的選項-這可以通過std::find輕松完成。 如果這是您想要的,請進行說明。

當您的班級按字段val排序時,您有以下選擇:

  • 遍歷所有元素並通過std::findstd::find_if查找具有特定ID的std::find_if
  • 創建另一個容器並按ID排序(可能使用std :: share_ptr以避免重復)
  • 使用boost::multiindex並通過valid創建索引

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM