2011-02-03 75 views
0

我想在std :: list中找到特定對象,其中對象的屬性符合輸入參數。如何在STL容器中查找特定對象

我發現一個解決方案使用find(。)或find_if(。)一元謂詞,但我需要一個二元函數。

爲什麼我不能讓迭代器作爲對象的引用(如java)並通過引用檢查字段?有沒有辦法做到這一點不使用find/find_if ...

+1

您正在使用哪種編譯器?如果它是最近的GCC或VC版本,它將實現(下一版C++標準的)lambda函數,這使得這更容易。 – sbi 2011-02-03 21:34:42

回答

8

我發現一個解決方案使用find(。)或find_if(。)一元謂詞,但在我需要一個二元函數。

不 - 你需要一元謂詞 - 畢竟find_if功能只能一個對象(當前對象列表中的)進行比較。你的斷言需要知道哪個屬性值來比較:

struct compare_with { 
    int attr_value; 
    compare_with(int attr_value) : attr_value(attr_value) { } 

    bool operator()(your_object const& obj) const { return obj.attr == attr_value; } 
}; 

現在你可以調用find_if

result = find_if(your_list.begin(), your_list.end(), compare_with(some_value)); 

爲什麼我不能只是讓迭代器是對象的引用(像java),並通過參考檢查領域?

你可以。但是,這絕對不清楚你的意思。只需遍歷列表。

2

是的,你可以這樣做:

list<myclass>::iterator i; 
for(i = mylist.begin(); i != mylist.end(); ++i) 
{ 
    if(i->field == value_to_check_for) 
     break; 
} 

// now i is an iterator pointing to the object if it was found 
// or mylist.end() if it wasn't 

但當然,我不明白你爲什麼會需要一個二元謂詞如果您一次只檢查一個對象。