2013-03-07 30 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