为什么我的仿函数成员变量"重置"?(C++)

Lor*_*ton 2 c++ functor

我正在学习如何使用仿函数,所以我创建了一个,我不明白为什么我的计数器变量在程序结束时为0.

这里的代码:

#include"stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<list>


using namespace std;

class myFunctor {
public:
    myFunctor():counter(0) {}
    void operator()(int i) { cout << "in the functor: " << i ; counter++; cout << "   counter=" << counter << endl; }
    int getCounter() const { return counter; }
private:
    int counter;
};

int main()
{
    vector<int> v{ 1,2,3,4,5,6,7,8,9,10 };
    myFunctor f;

    for_each(v.begin(), v.end(), f);

    cout << "counter=" << f.getCounter() << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

in the functor: 1   counter=1
in the functor: 2   counter=2
in the functor: 3   counter=3
in the functor: 4   counter=4
in the functor: 5   counter=5
in the functor: 6   counter=6
in the functor: 7   counter=7
in the functor: 8   counter=8
in the functor: 9   counter=9
in the functor: 10   counter=10
counter=0
Run Code Online (Sandbox Code Playgroud)

Cur*_*ous 8

如果您查看签名,for_each您将看到它按值接受仿函数,因此for_each当算法终止时,您在内部看到的更改不会反映在外部.

http://en.cppreference.com/w/cpp/algorithm/for_each

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
Run Code Online (Sandbox Code Playgroud)

如果要进行此工作,则必须使用std::ref生成引用包装并按值传递.

std::for_each(vec.begin(), vec.end(), std::ref(functor));
Run Code Online (Sandbox Code Playgroud)

看看在对文档std::refreference_wrapper看如何以及为什么这个工程(关键的一点是,std::reference_wrapper有一个operator()与仿函数工作http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator()).

  • 或者,或者,捕获`for_each`的返回值. (4认同)