accumulate與自定義資料型別
阿新 • • 發佈:2019-02-02
C++ STL中有一個通用的數值型別計算函式— accumulate(),可以用來直接計算陣列或者容器中C++內建資料型別,例如:
- #include <numeric>
- int arr[]={10,20,30,40,50};
- vector<int> va(&arr[0],&arr[5]);
- int sum=accumulate(va.begin(),va.end(),0); //sum = 150
但是對於自定義資料型別,我們就需要自己動手寫一個類來實現自定義資料的處理,然後讓它作為accumulate()的第四個引數,accumulate()的原型為(檔案取自DEV-C++編譯器):
- template<typename _InputIterator, typename _Tp, typename _BinaryOperation>
- _Tp accumulate(_InputIterator __first, _InputIterator __last, _Tp __init,
- _BinaryOperation __binary_op)
- {
- // concept requirements
-
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator
- __glibcxx_requires_valid_range(__first, __last);
- for ( ; __first != __last; ++__first)
- __init = __binary_op(__init, *__first);
- return __init;
- }
第四個引數為 __binary_op ,我們需要重寫這個函式物件,後面還會繼續分析...
假設自定義資料型別為:
- struct Student
- {
- string name; // 學生姓名
-
int total; // 四級分數
- };
- #include <iostream>
- #include <algorithm>
- #include <numeric>
- #include <vector>
- #include <string>
- using namespace std;
- struct Student
- {
- string name;
- int total;
- };
- class PS{
- public:
- int operator()(int t1,const Student& t2)
- {
- return (t1 + t2.total);
- }
- };
- int main()
- {
- Student student[3]={
- {"hicjiajia",10},
- {"sijikaoshi",20},
- {"what",40}
- };
- int sum=accumulate(&student[0],&student[3],0,PS());
- cout<<sum<<endl;
- system("pause");
- return 0;
- }