std::accumulate的用法(轉)


std :: accumulate
累計范圍內的值
返回將范圍中的所有值累加[first,last)到init的結果。

默認操作是向上添加,但可以將不同的操作指定為binary_op。

accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
1
參數
first,last:
將迭代器輸入到序列中的初始位置和最終位置。使用的范圍是[first,last),它包含所有的元件第一和最后一個,包括由指向的元件第一但不被指向的元素最后。

init
累加器的初始值。

binary_op
myfunction (int x, int y);這樣的函數時,init傳入x,前面的范圍和傳入y,最后返回函數值。
std::minus();返回init-范圍和
int operator()(int x, int y);和函數那個一樣效果。

返回值
累積init:和范圍內所有元素的結果[first,last)。

// accumulate example

#include <iostream> // std::cout
#include <functional> // std::minus
#include <numeric> // std::accumulate

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
int init = 100;
int numbers[] = {10,20,30};

std::cout << "using default accumulate: ";
std::cout << std::accumulate(numbers,numbers+3,init);
std::cout << '\n';

std::cout << "using functional's minus: ";
std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
std::cout << '\n';

std::cout << "using custom function: ";
std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
std::cout << '\n';

std::cout << "using custom object: ";
std::cout << std::accumulate (numbers, numbers+3, init, myobject);
std::cout << '\n';

return 0;
}

編輯並運行

輸出:

使用默認累積:160
使用函數的減號:40
使用自定義功能:220
使用自定義對象:280
————————————————
版權聲明:本文為CSDN博主「臭屁淇」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_21567767/article/details/82023752


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM