c++ - Summing vector elements in a for loop, and reset the summing after certain number of vector elements
问题描述
Let's define two vectors, their size is 30. I want to push_back to the summed value of the vector2
, in the range of the vec1
elements: 1-6, 7-12,13-18,19-24.
Which means, I reset the summed value from vec2, once the vec1
elements 6, 12, 18 and so on complete (including their repetition).
For example, the first sum from vector2 will be completed at vec2[19]
, because of the elements of the vec1
6 ends at that position. Then we can reset the sum =0, and start over in the same fashion. Each step I would like to push_back the sum to a new vector and carry on the process.
#include<iostream>
#include<vector>
using namespace std;
// return type vector
int main(){
vector<double> summed;
int limit = 6;
double sum = 0;
vector <int> vec1 {1,1,1,1,1,2,3,3,3,3,3,3,3,3,4,4,4,6,6,6,10,10,10,10,12,13,14,14,15,16,20};
vector <double> vec2 {100,1,1200,1130,1140,20,3,32,33,34.0,3,23,3,33,4,43,4,6,36,64,1201,10,120,10,12,13,14,124,125,16,20};
for (int i = 0; i < vec2.size(); ++i)
if (vec1[i] <= limit)
sum += vec2[i];
else
{
summed.push_back(sum);
limit += 6;
sum = vec2[i];
}
for (int i =0; i<=summed.size(); i++)
{
cout << " the elements of the summed vector "<<summed[i] <<endl;
}
}
OUTPUT:
the elements of the summed vector 3912
the elements of the summed vector 1353
the elements of the summed vector 292
the elements of the summed vector 0
Four groups from the vec1
elements
1,1,1,1,1,2,3,3,3,3,3,3,3,3,4,4,4,6,6,6,
10,10,10,10,12,
13,14,14,15,16,
20
解决方案
如果我正确理解你的问题,这就是你要找的:
vector<double> summed;
int limit = 6;
double sum = 0;
for (int i = 0; i < vec2.size(); ++i)
{
if (vec1[i] <= limit)
sum += vec2[i];
else
{
summed.push_back(sum);
limit += 6;
sum = vec2[i];
}
}
summed.push_back(sum);
请注意,这是假设vec1
按非降序排序的。
推荐阅读
- java - Android Studio:在没有按钮的情况下添加两个数字
- python - 有没有办法找到一个字符串中某个标签的所有索引相对于删除标签的同一字符串?
- amazon-web-services - 将多服务应用程序部署到云提供商
- c# - Linq 对于谓词和 order by 子句非常慢
- facebook - Facebook Graph API 总是返回 0 作为 CARE 反应的计数
- html - 计时器(用于倒计时)
- python - 马拉雅拉姆语词的词形还原
- python - 如何在 Python 中使用命令行运行可执行文件?
- javascript - 在 vue.js 中与其他表单内容一起上传照片
- html - height:100% 无论我将它应用于什么元素,它似乎都不起作用