用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

使用一个函数对象来保存状态

2012-11-27 作者: 程序猿style举报

[c++]代码库

// 使用一个函数对象来保存状态
#include <algorithm>
#include <iostream>
#include <vector>
#include <list>
 
using namespace std;
 
template<typename elementType>
struct DisplayElementKeepCount {
    // Hold the count in a member variable
    int m_nCount;
 
    // Constructor
    DisplayElementKeepCount() {
        m_nCount = 0;
    }
 
    // Display the element, hold count!
    void operator ()(const elementType& element) {
        ++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;
 
    // Display the array of integers
    DisplayElementKeepCount<int> mResult;
    mResult = for_each(vecIntegers.begin() // Start of range
            , vecIntegers.end() // End of range
            , DisplayElementKeepCount<int>()); // function object
 
    cout << endl << endl;
 
    // Use the state stores in the return value of for_each!
    cout << "'" << mResult.m_nCount << "' elements were displayed!" << endl;
 
    return 0;
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...