用 C++ 中的硬編碼元素初始化 std::vector 的最簡單方法是什麼?


在現代 C++ [11,14,…] 中,以下方法可初始化向量

std::vector<int> vec = {1,2,3};

演算法

Begin
   Initialize the vector v.
   Using accumulate, sum up all the elements of the vector v is done.
   Print the result.
End.

以下是一個簡單示例,用於求出向量的各個元素之和

示例

 即時演示

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
   vector<int> v = {2,7,6,10};
   cout<<"Sum of all the elements are:"<<endl;
   cout<<accumulate(v.begin(),v.end(),0);
}

輸出

Sum of all the elements are:
25

更新於:30-07-2019

564 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告