我试图使用find()方法在集合中找到一个对象。但是,我无法做到这一点似乎我发送了一个错误的密钥。什么是正确的方法呢?
#include <iostream>
#include <set>
#include <utility>
struct Class {
std::pair<int,int> data;
int val = 0;
int id = 0; ///ID for the object
};
struct CompClass {
bool operator() (const Class& lhs, const Class& rhs) const
{
if (lhs.data.first == rhs.data.first) return lhs.data.second < rhs.data.second;
return lhs.data.first<rhs.data.first;
}
};
int main ()
{
Class c1,c2,c3,c4;
c1.val = 92;c1.id = 2; c1.data = std::make_pair(92,2);
c2.val = 94;c2.id = 3; c2.data = std::make_pair(94,3);
c3.val = 92;c3.id = 1; c3.data = std::make_pair(10,1);
std::set<Class,CompClass> 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::make_pair(92,2) ) != fifth.end() ) {std::cout << "Got it";} //Error
return 0;
}
答案 0 :(得分:2)
std::set<T>::find
在C ++ 11中采用T
类型的参数。您需要提供Class
对象,而不是std::pair
:
if (fifth.find( Class{92,2,0,0} ) != fifth.end() ) {std::cout << "Got it";}