用 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 次浏览

开启你的职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.