2013-03-07 47 views
0

我有這個結構的節點列表:如何搜索STL的list項目的相關Alghorithm查找()

private: 
    char namefield[30]; 
    char tam[3]; 
    char type[1]; 
}; 

我想找到和元素與alghorithm類的查找功能,但我想這樣做與該項目的名稱屬性,find函數有一個項目可以查找作爲參數,但事情是,我想發送節點的屬性,而不是節點本身。

回答

0

您可以使用find_if函數http://www.cplusplus.com/reference/algorithm/find_if/。您爲結構定義一個謂詞(比較函數),如果兩個結構的名稱域都爲真,則返回true。 或者類似的東西

class Cmp : public std::unary_function<mystruct, bool> { 
    std::string m_str; 
public: 
    Cmp(const std::string &str) : m_str(str) {} 
    bool operator()(const mystruct &val) const { 
     return m_str.compare(val.namefield) ==0; 
    } 
}; 

std::find_if(cont.begin(), cont.end(), Cmp("foo")); 

其中cont是你的結構的容器

+0

@ChristianRau感謝編輯 – Michael 2013-03-07 11:44:53