What would be the key in case of Objects being inserted into std::set? As for the following example, I am inserting objects of class Classcomp into the std::set. However, I want to find whether an object of Classcomp with a particular 'id = 1' exists in the std::set or not?
#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;
}
Sets is different from the map by exactly the fact that values of objects inside the set are their keys . If you need to separate a key from the value, you need a key-value container, such as std::map
or std::unordered_map
.
Clarification I am not talking about the option of simply iterating over all objects in the set and checking every object to have specified key - which is easily done with std::find
. If that's what you want, please clarify.
As your class is sorted by field val
you have following options:
std::find
or std::find_if
boost::multiindex
and create index by val
as well as id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.