如何使用 C++ 中的 STL 查詢向量中元素的和?


在本教程中,我們將討論一個程式,瞭解如何使用 C++ 中的 STL 查詢向量中元素的和。

要查詢給定向量的元素之和,我們將使用 STL 庫中的 accumulate() 方法。

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   //defining the vector
   vector<int> a = { 1, 45, 54, 71, 76, 12 };
   cout << "Vector: ";
   for (int i = 0; i < a.size(); i++)
      cout << a[i] << " ";
   cout << endl;
   //calculating sum of the elements
   cout << "Sum = "<< accumulate(a.begin(), a.end(), 0);
   return 0;
}

輸出

Vector: 1 45 54 71 76 12
Sum = 259

更新於: 2020 年 2 月 25 日

667 瀏覽

開啟你的職業生涯

完成課程獲得認證

開始吧
廣告