1. 程式人生 > 實用技巧 >STL的accumulate用法

STL的accumulate用法

std::accumulate

該函式定義於標頭檔案 ,它主要用於累加求和和自定義資料型別的處理。

template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );
template< class InputIt, class T, class BinaryOperation >
constexpr T accumulate( InputIt first, InputIt last, T init, BinaryOperation op );

累加求和

accumulate函式有三個引數,前兩個引數指定元素範圍,第三個是累加的初值。


比如現在要求a+b,可以這麼來寫:

int main()
{
    vector<string> v;
    int a,b;
    cin >> a >> b;
    v.push_back(a);v.push_back(b);
    int sum = accumulate(v.begin(),v.end(),0);
    cout << sum << endl;
}

該函式也可以用來進行字串的拼接,下面程式碼的作用是拼接a字串和b字串。

int main()
{
    vector<string> v;
    string a,b;
    cin >> a >> b;
    v.push_back(a);v.push_back(b);
    string sum = accumulate(v.begin(),v.end(),string(""));
    cout << sum << endl;
}

自定義資料型別的處理

我們將自定義的結構體Node的數值進行累加。

struct Node
{
    string Name;
    int score;
};

vector<Node> tr = {
    {"zhangsan",100},
    {"lisi",200},
    {"wangwu",300}
};

int main()
{
    int sum1 = accumulate(tr.begin(),tr.end(),0,[](int a,Node b){return a + b.score;});
    cout << sum1 << endl;
}