[英]How do I call a object's member function as a unary_function for std algorithms?
I have a class that looks like this. 我有一个看起来像这样的课程。
class A
{
public:
void doSomething();
}
I have an array of these classes. 我有这些类的数组。 I want to call doSomething() on each item in the array.
我想在数组中的每个项目上调用doSomething()。 What's the easiest way to do this using the algorithms header?
使用算法标题最简单的方法是什么?
Use std::mem_fun_ref to wrap the member function as a unary function. 使用std :: mem_fun_ref将成员函数包装为一元函数。
#include <algoritm>
#include <functional>
std::vector<A> the_vector;
...
std::for_each(the_vector.begin(), the_vector.end(),
std::mem_fun_ref(&A::doSomething));
You can also use std::mem_fun if your vector contains pointers to the class, rather than the objects themselves. 如果向量包含指向类的指针而不是对象本身,也可以使用std :: mem_fun。
std::vector<A*> the_vector;
...
std::for_each(the_vector.begin(), the_vector.end(),
std::mem_fun(&A::doSomething));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.