如何使用STL在C ++中找到向量元素的和
给定一个向量,在C ++中使用STL找到该向量的元素之和。
示例:
输入: vec = {1, 45, 54, 71, 76, 12}
输出: 259
输入: vec = {1, 7, 5, 4, 6, 12}
输出: 35
方法:
可以使用STL中提供的accumulate()函数找到和。
语法:
accumulate(first_index,last_index,initial value of sum);
// C ++程序使用accumulate()在STL中查找数组的总和
#include
using namespace std;
int main()
{
// 获取矢量
vector a = {1,45,54,71,76,12};
//打印向量
cout <<“ Vector:”;
for(int i = 0; i
输出
向量:1 45 54 71 76 12
总和= 259
时间复杂度: 它是介于first_index和last_index之间距离的线性,即如果您的向量包含两个给定索引之间的n个元素,则时间复杂度为O(n)。
辅助空间: O(1)
另一种方法:(使用for_each()功能)
for_each() 函数是一个STL算法,它将给定的函数应用于由一对迭代器定义的范围中的每个元素。
要使用 for_each() 函数查找向量中所有元素的总和,我们可以定义一个lambda函数或函数对象将每个元素添加到运行总数中。
语法:
for_each(InputIt first,InputIt last,UnaryFunction f);
// C ++程序使用for_each()函数在STL中查找数组的总和
# include
using namespace std;
int main()
{
// 获取矢量
vector a = {1,45,54,71,76,12};
int sum = 0;
//打印向量并计算总和
cout <<“ Vector:”;
for_each(a.begin(),a.end(),[&](int i){
cout << i <<“”;
sum + = i;
});
//打印向量的总和
cout <<“ \ n总和=“<< sum << endll;
返回0;
}
产量
向量:1 45 54 71 76 12
总和= 259
时间复杂度: O(N),其中N是范围内的元素数量。
辅助空间: O(1)