c++ - 为什么我的仿函数成员变量 "reset"? (c++)

标签 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;
}

结果如下:

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

最佳答案

如果您查看 for_each 的签名,您会发现它按值接受仿函数,因此您在 for_each 中看到的更改不会在外部反射(reflect)出来算法终止。

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

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

如果你想完成这项工作,你将不得不使用 std::ref 来生成一个引用包装器并按值传递它。

std::for_each(vec.begin(), vec.end(), std::ref(functor));

查看 documentation for std::refreference_wrapper 以了解其工作原理和原因(关键是 std::reference_wrapper 有一个 operator() 与仿函数 http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator() 一起工作)。

关于c++ - 为什么我的仿函数成员变量 "reset"? (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45310152/

相关文章:

c++ - 在 boost::spirit 中正确设置 expectation_failure 的跨度

c++ - 如何推断模板中的 C++ 返回类型?

c++ - 通过标准算法。模板推导

c++ - 正确使用 C++ STL 线程的仿函数

c++ - 如何在源文件中实现嵌套类构造函数

c++ - 为什么我不能在 Windows 上使用 boost::locale::conv::between 将 UTF-16 文本转换为其他编码

c++ - Qt Creator 添加 mqtt 库

c++ - 在 C++ 中创建 MakeFile

javascript - 了解仿函数法则 0​​x104567911