我必须经常做的事情是在元素集合中找到一个具有给定值的元素的成员。例如给出:
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/