qfedu-cpp-level/day9/homework/h2.cpp

28 lines
577 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 【场景】向量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;
}