Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,106 questions

40,778 answers

573 users

How to implement vector partial sum in C++

1 Answer

0 votes
#include <iostream>  
#include <vector> 

using std::vector;
using std::cout;
using std::endl;

void partial_sum(vector<int> v1, vector<int> &v2)
{
	/*
	v2[0] = v1[0] = 0
	v2[1] = v1[0] + v1[1] = 0 + 1 = 1
	v2[2] = v1[0] + v1[1] + v1[2] = 0 + 1 + 2 = 3
	v2[3] = v1[0] + v1[1] + v1[2] + v1[3] = 0 + 1 + 2 + 3 = 6
	v2[4] = v1[0] + v1[1] + v1[2] + v1[3] + v1[4] = 0 + 1 + 2 + 3 + 4 = 10
	*/

	for (int i = 0; i < v1.size(); i++)
		for (int j = 0; j <= i; j++)
			v2[i] += v1[j];
}

int main()
{
	vector<int> v1{ 0, 1, 2, 3, 4 }, v2{ 0, 0, 0, 0, 0 };

	partial_sum(v1, v2);

	for (int i = 0; i < v2.size(); i++)
		cout << v2[i] << " ";

	cout << endl;

	return 0;
}

/*
run:

0 1 3 6 10

*/

 





answered Apr 24, 2018 by avibootz
...