2014-02-08 24 views
0

我有一個Holiday查找屬性==一定的價值,使用find方法

class Holiday 
{ 
    public: 


    private: 
     string id; 
     string destinationCode; 
     string destinationName; 

}; 

我試圖用find方法來查找是否有任何Holiday對象中的Holiday含有載體屬性:它等於H001

此字符串ID是什麼,我都試過

vector<Holiday>::iterator h1; 
    vector<Holiday>::iterator h2; 
    vector<Holiday>::iterator h3; 


    h1 = this->holidayPackages.begin(); 
    h2 = this->holidayPackages.end(); 

    h3=find(h1,h2,"H001"); 

我得到一個編譯錯誤

錯誤C2678:二進制「==」:沒有操作員發現這需要左手 數類型的「假日」

如何找到屬性一個Holiday對象使用find方法?

編輯:我在尋找一個NON C++11 answer

回答

3

find模板需要定義的operator==。所以,試試這個:

bool Holiday::operator==(const string& other) const { 
    return id == other; 
} 

也不要忘記在類中聲明該運營商:

class Holiday 
{ 
    public: 
     bool operator==(const string& other) const; 

    private: 
     string id; 
     string destinationCode; 
     string destinationName; 

}; 
0

你的迭代器是Holiday實例,但你嘗試將Holidayconst char*比較當致電find。如何編譯器知道它應該與id比較字符串,而不是與destinationCodedestionationName

如果你已取得了C++ 11可以使用lambda:

auto it=std::find_if(h1, h2, [](const Holiday &h){return h.id=="H001";}); 
2

你不能使用std::find在不同類型的項目列表進行搜索,但你可以用std::find_if,像這樣:

h3 = find_if(h1, h2, [] (const Holiday& h) { return h.id == "H001"; }); 

注:以上使用lambda語法,這是不可用之前C++ 11。如果您的編譯器不是C++ 11兼容的,您需要提供一個「常規」函數來比較id與目標值。

2

如果你沒有==操作符和不利用C++ 11:

#include <algorithm> 
#include <iostream> 

class Holiday 
{ 
    public: 
    const std::string& get_id() const { return id; } 

    private: 
    std::string id; 
    std::string destinationCode; 
    std::string destinationName; 

}; 


int main() 
{ 
    std::vector<Holiday> holidays; 

    struct Predicate { 
     bool operator() (const Holiday& holiday) { 
      return holiday.get_id() == "H001"; 
     } 
    }; 

    std::find_if(holidays.begin(), holidays.end(), Predicate()); 
} 
0

查找功能需要一個==操作符來檢查東西在矢量等於第三個參數,從而定義了一個==您的班級中的操作員是這樣的:

bool operator==(const string& other) const { 
    return id == other; 
}