64,636
社区成员
发帖
与我相关
我的任务
分享
#include "algorithm"
#include "iostream"
#include "vector"
#include "list"
using namespace std;
template <typename elementType>
struct DisplayElementKeepCount
{
int m_nCount;
DisplayElementKeepCount() // 为什么这个会输出2次后才执行下面的operator??
{
cout<<"hello world"<<endl;
m_nCount = 0;
}
void operator()(const elementType & element) //这样写DisplayElementKeepCount<int>(),为什么就会指向该operator?
{
++m_nCount;
cout<<element<<' ';
}
};
int main()
{
vector<int> vecIntegers;
for(int nCount =0; nCount<10; ++nCount)
vecIntegers.push_back(nCount);
cout<<"Displaying the vector of integers: " <<endl;
DisplayElementKeepCount<int> mResult;
mResult = for_each(vecIntegers.begin(), vecIntegers.end(), DisplayElementKeepCount<int>());
cout<<endl<<endl;
cout<<"'" << mResult.m_nCount<< "' elements were displayed!"<<endl;
return 0;
}
DisplayElementKeepCount<int> x;
x(); //x.m_count = 1;
x(); //x.m_cout = 2;
DisplayElementKeepCount<int> mResult; //1
mResult = for_each(vecIntegers.begin(), vecIntegers.end(), DisplayElementKeepCount<int>() //2
);
因为你构造了两次呀 DisplayElementKeepCount<int> mResult; // 这里构造了一个
mResult = for_each(vecIntegers.begin(), vecIntegers.end(), DisplayElementKeepCount<int>()); 这里有构造了一个
可以改成
DisplayElementKeepCount<int> mResult;
mResult = for_each(vecIntegers.begin(), vecIntegers.end(), mResult);