2016-02-23 20 views
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; 
} 
+0

您是否收到錯誤?錯誤的結果? – NathanOliver

+2

'std :: pair <>'已經有'operator <'定義完全按照你使用它的方式,所以只需寫'return lhs.data Slava

+0

@Slava:注意到(謝謝)。 – letsBeePolite

回答

2

std::set<T>::find需要T類型的在C++ 11的參數。您需要提供Class對象,而不是std::pair

if (fifth.find( Class{92,2,0,0} ) != fifth.end()) {std::cout << "Got it";} 
+3

在C++ 14中有過載需要任何東西,但是您需要定義與其他類型的比較並使比較器透明。 –

相關問題