c++ - 算法在容器中找到一个元素,该元素的一个成员具有给定值

标签 c++ boost member-functions boost-range non-member-functions

我必须经常做的事情是在元素集合中找到一个具有给定值的元素的成员。例如给出:

class Person
{
   string getName() const {return mName;}
   private:
   string mName;
};

std::vector<Person> people;

我想找到名字叫“Alice”的人。一种方法是(使用 boost 范围适配器):

string toFind = "Alice";
auto iterator = find(people | transformed([](Person const & p){p.getName()}) , toFind );

对于如此简单的操作,有很多样板文件。难道不应该做这样的事情吗:

string toFind = "Alice";
auto iterator = find(people | transformed(&Person::getName) , toFind ); 

(不编译因为 &Person::getName 不是一元函数)

有没有简单的方法来获取成员的一元函数?

最佳答案

您可以使用 std::find_if具有适当的功能 lambda它检查 getName() 值是否等于 tofind string:

std::string tofind = "Alice";
auto it = std::find_if(people.begin(), people.end(), [&tofind](const Person& o) {return o.getName() == tofind; });
if (it != std::end(people)) {
    std::cout << "Contains: " << tofind << '\n';
}
else {
    std::cout << "Does not contain: " << tofind << '\n';
}

这需要 getName 函数位于 public 类范围内,您应该提供适当的构造函数。完整代码为:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

class Person {
public:
    Person(const std::string& name) : mName{ name } {}
    std::string getName() const { return mName; }
private:
    std::string mName;
};

int main() {
    std::vector<Person> people{ {"John"}, {"Alice"}, {"Jane"} };
    std::string tofind = "Alice";
    auto it = std::find_if(people.begin(), people.end(), [&tofind](const Person& o) {return o.getName() == tofind; });
    if (it != std::end(people)) {
        std::cout << "Contains: " << tofind << '\n';
    }
    else {
        std::cout << "Does not contain: " << tofind << '\n';
    }
}

关于c++ - 算法在容器中找到一个元素,该元素的一个成员具有给定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49192649/

相关文章:

c++ - MySQL C++ 连接器在使用 BLOB 执行 INSERT 时崩溃

c++ - 编译器/链接器错误 "undefined reference"

c++ - boost 多边形差异返回交集

c++ - Boost 单元测试框架 dll 导出的 std::basic_ostringstream 导致 "already defined symbol"-error

c++ - 变量内部变量的问题一旦更改就会恢复

c++ - 没有类声明的友元成员函数

c++ - Visual C++ 编译和生成巨大目标文件的嵌套 lambda 表达式非常慢

c++ - 如何在 C++ 中初始化静态 vector 数组成员

c++ - 如何将输出重定向到 boost 日志?

c++ - 模板成员函数仅在调用时实例化