[英]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的std::find_if
boost::multiindex
並通過val
和id
創建索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.