【问题标题】:How to Search Stl List Item With Alghorithm Find()如何使用算法 Find() 搜索 Stl 列表项
【发布时间】:2013-03-07 01:32:00
【问题描述】:

我有一个具有这种结构的节点列表:

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

我想使用算法类中的 find 函数来查找和元素,但我想用项目的 namefield 属性来做,find 函数有一个项目作为参数要查找,但事情是我想要发送节点的属性而不是节点本身..

【问题讨论】:

    标签: list stl find


    【解决方案1】:

    您可以使用find_if 函数http://www.cplusplus.com/reference/algorithm/find_if/。你为你的结构定义一个谓词(比较函数),如果两个结构的名称字段都为真,则返回真。 或者类似的东西

    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 是你的结构的容器

    【讨论】:

      猜你喜欢
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 2019-08-12
      相关资源
      最近更新 更多