1
我想用find()方法找到一個對象裏面的對象。但是,我無法做到這一點,似乎我發送了一個錯誤的密鑰。什麼是正確的方式來做到這一點?在std :: set中找到一個對象時出錯
#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;
}
您是否收到錯誤?錯誤的結果? – NathanOliver
'std :: pair <>'已經有'operator <'定義完全按照你使用它的方式,所以只需寫'return lhs.data
Slava
@Slava:注意到(謝謝)。 – letsBeePolite