1. 程式人生 > >accumulate與自定義資料型別

accumulate與自定義資料型別

C++ STL中有一個通用的數值型別計算函式— accumulate(),可以用來直接計算陣列或者容器中C++內建資料型別,例如:
  1. #include <numeric>
  2. int arr[]={10,20,30,40,50};  
  3. vector<int> va(&arr[0],&arr[5]);  
  4. int sum=accumulate(va.begin(),va.end(),0);  //sum = 150

但是對於自定義資料型別,我們就需要自己動手寫一個類來實現自定義資料的處理,然後讓它作為accumulate()的第四個引數,accumulate()的原型為(檔案取自DEV-C++編譯器):

  1. template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
  2.  _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init,  
  3.             _BinaryOperation __binary_op)  
  4.  {  
  5.      // concept requirements  
  6.      __glibcxx_function_requires(_InputIteratorConcept<_InputIterator
    >)  
  7.     __glibcxx_requires_valid_range(__first, __last);  
  8.     for ( ; __first != __last; ++__first)  
  9.        __init = __binary_op(__init, *__first);  
  10.     return __init;  
  11.  }  

第四個引數為 __binary_op ,我們需要重寫這個函式物件,後面還會繼續分析...

假設自定義資料型別為:

  1. struct Student  
  2. {  
  3.       string name;   // 學生姓名  
  4.        int total;      // 四級分數  
  5. };  
那麼我們可能要定義如下列的類:
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <numeric>
  4. #include <vector>
  5. #include <string>
  6. using namespace std;  
  7. struct Student  
  8. {  
  9.        string name;  
  10.        int total;  
  11. };  
  12. class PS{  
  13.  public:  
  14.         int operator()(int t1,const Student& t2)  
  15.         {  
  16.             return (t1 + t2.total);  
  17.         }  
  18. };  
  19. int main()  
  20. {  
  21.     Student student[3]={  
  22.             {"hicjiajia",10},  
  23.             {"sijikaoshi",20},  
  24.             {"what",40}  
  25.             };  
  26.     int sum=accumulate(&student[0],&student[3],0,PS());  
  27.     cout<<sum<<endl;  
  28.     system("pause");  
  29.     return 0;  
  30. }