[C++] 使用一个函数对象来保存状态 →→→→→进入此内容的聊天室

来自 , 2019-12-11, 写在 C++, 查看 129 次.
URL http://www.code666.cn/view/4e87337f
  1. // 使用一个函数对象来保存状态
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <vector>
  5. #include <list>
  6.  
  7. using namespace std;
  8.  
  9. template<typename elementType>
  10. struct DisplayElementKeepCount {
  11.         // Hold the count in a member variable
  12.         int m_nCount;
  13.  
  14.         // Constructor
  15.         DisplayElementKeepCount() {
  16.                 m_nCount = 0;
  17.         }
  18.  
  19.         // Display the element, hold count!
  20.         void operator ()(const elementType& element) {
  21.                 ++m_nCount;
  22.                 cout << element << ' ';
  23.         }
  24. };
  25.  
  26. int main() {
  27.         vector<int> vecIntegers;
  28.  
  29.         for (int nCount = 0; nCount < 10; ++nCount)
  30.                 vecIntegers.push_back(nCount);
  31.  
  32.         cout << "Displaying the vector of integers: " << endl;
  33.  
  34.         // Display the array of integers
  35.         DisplayElementKeepCount<int> mResult;
  36.         mResult = for_each(vecIntegers.begin() // Start of range
  37.                         , vecIntegers.end() // End of range
  38.                         , DisplayElementKeepCount<int>()); // function object
  39.  
  40.         cout << endl << endl;
  41.  
  42.         // Use the state stores in the return value of for_each!
  43.         cout << "'" << mResult.m_nCount << "' elements were displayed!" << endl;
  44.  
  45.         return 0;
  46. }
  47.  

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

这儿你可以回复上面这条便签

captcha