28 lines
577 B
C++
28 lines
577 B
C++
|
// 【场景】向量vector求和
|
|||
|
// 编写一个函数 sumVector,接受一个整数向量作为参数,并返回向量中所有元素的和。
|
|||
|
|
|||
|
#include <iostream>
|
|||
|
#include <vector>
|
|||
|
|
|||
|
using namespace std;
|
|||
|
|
|||
|
int sumVector(vector<int> &vec)
|
|||
|
{
|
|||
|
int sum = 0;
|
|||
|
vector<int>::iterator it = vec.begin();
|
|||
|
while (it != vec.end())
|
|||
|
{
|
|||
|
sum += *it;
|
|||
|
it++;
|
|||
|
}
|
|||
|
return sum;
|
|||
|
}
|
|||
|
|
|||
|
int main()
|
|||
|
{
|
|||
|
vector<int> v;
|
|||
|
for (int i = 0; i < 10; i++)
|
|||
|
v.push_back(i);
|
|||
|
cout << "向量中所有元素的和为: " << sumVector(v) << endl;
|
|||
|
return 0;
|
|||
|
}
|