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

C++ 算法在容器中找到一个元素,该元素的一个成员具有给定的值,c++,boost,member-functions,boost-range,non-member-functions,C++,Boost,Member Functions,Boost Range,Non Member Functions,我经常要做的一件事是在元素集合中找到一个成员,这个元素有一个给定值的元素。例如: class Person { string getName() const {return mName;} private: string mName; }; std::vector<Person> people; 对于这样一个简单的操作,这是大量的样板文件。难道不可能做以下事情吗: string toFind = "Alice"; auto iterator = find(peo

我经常要做的一件事是在元素集合中找到一个成员,这个元素有一个给定值的元素。例如:

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

std::vector<Person> people;
对于这样一个简单的操作,这是大量的样板文件。难道不可能做以下事情吗:

string toFind = "Alice";
auto iterator = find(people | transformed(&Person::getName) , toFind ); 
未编译,因为&Person::getName不是一元函数

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

您可以将该函数与适当的函数一起使用,该函数检查getName值是否等于tofind string:

您可以使用适当的函数,该函数检查getName值是否等于tofind string:


你要找的是。它包装了一个指向成员函数的指针,这样就可以像调用自由函数一样调用它,其中调用成员函数的对象作为第一个参数传递。在您的示例中,您可以像这样使用它:

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

你要找的是。它包装了一个指向成员函数的指针,这样就可以像调用自由函数一样调用它,其中调用成员函数的对象作为第一个参数传递。在您的示例中,您可以像这样使用它:

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

嗨,罗恩!,是的,这很好,但我想它携带了太多的样板文件,我想要更紧凑的东西,比如:find_if people,unary_compare&Person::getName,alice Hi Ron!,是的,这很好,但我想它携带了太多的样板文件,我想要更紧凑的东西,比如:find_if people,一元比较&Person::getName,alice Thank you@xskxzr,这正是我想要的:Thank you@xskxzr,这正是我想要的:
#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';
    }
}
string toFind = "Alice";    
auto iterator = find(people | transformed(std::mem_fn(&Person::getName)) , toFind ); 
                                       // ^^^^^^^^^^^