求助这个代码是什么意思?

jdynnwxs 2015-09-01 05:55:42

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

}

...全文
99 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
mujiok2003 2015-09-01
  • 打赏
  • 举报
回复
引用
void operator()(const elementType & element) //这样写DisplayElementKeepCount<int>(),为什么就会指向该operator? { ++m_nCount; cout<<element<<' '; }
不是这个原因。 这是个函数调用运算符的重载.


DisplayElementKeepCount<int> x;
x(); //x.m_count = 1;
x();  //x.m_cout = 2;
mujiok2003 2015-09-01
  • 打赏
  • 举报
回复
DisplayElementKeepCount<int> mResult; //1
    mResult = for_each(vecIntegers.begin(), vecIntegers.end(), DisplayElementKeepCount<int>() //2
);
因为你构造了两次呀
fefe82 2015-09-01
  • 打赏
  • 举报
回复
    DisplayElementKeepCount<int> mResult; // 这里构造了一个
    mResult = for_each(vecIntegers.begin(), vecIntegers.end(), DisplayElementKeepCount<int>()); 这里有构造了一个
可以改成

    DisplayElementKeepCount<int> mResult;
    mResult = for_each(vecIntegers.begin(), vecIntegers.end(), mResult);

64,636

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧