首页 > 解决方案 > 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

标签: c++vector

解决方案


如果我正确理解你的问题,这就是你要找的:

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按非降序排序的。


推荐阅读