2017-07-25 74 views
2

我學習如何使用函數,所以我創建了一個,我不明白爲什麼我的計數器變量在程序結束時爲0。爲什麼我的函數成員變量「重置」? (C++)

這裏的代碼:

#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 
+1

你永遠不actualy修改什麼,但臨時副本,爲什麼你會想到什麼嗎? –

回答

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); 

如果你想使這個工作,你將不得不使用std::ref生成參考包裝和傳遞,通過價值。

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

看看的documentation for std::refreference_wrapper,看看如何以及爲什麼這個工程(關鍵的一點是,std::reference_wrapperoperator()與函子http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator()工作)。

+4

或者,也可以捕獲'for_each'的返回值。 – templatetypedef

0

雖然好奇的答案是最好的解決辦法,這裏是另一個問題:

class myFunctor { 
public: 
    myFunctor():counter(std::make_shared<int>(0)) {} 
    void operator()(int i) { cout << "in the functor: " << i ; ++*counter; cout << " counter=" << *counter << endl; } 
    int getCounter() const { return *counter; } 
private: 
    std::shared_ptr<int> counter; 
}; 
相關問題