I have written a code to do it I want to make the code more efficient and preferably shorter and also able to handle odd vectors.
Here is the code(Not including the headers,main,std and all that.)
vector<int> v = {list here};
int sum = 0;
int c = 0;
for(int x:v){
++c;
if(c <=2){
sum+=x;
if(c==2){
cout << sum <<endl;
}
}
else{
c = 1;
sum =0;
sum+=x;
}
}
if(c==1){
cout <<sum <<endl;
}
C is the counter.What I do is when looping through the vector,I increase the counter. And add the elements of vector while the counter is <= 2. And output the sum when counter reaches 2. So now it has outputted the sum of the first 2 numbers. When the counter reaches 3, I reset it to 1(Because 3 is the 1st number on the next pair). Then reset the sum and add 3 to sum. Then 4 will be handled by the first part of the code and so on. Now if the vector contains odd number of elements, the remaining number is just outputted in the last if statement block.
I just explained the code to make it easier to answer. I would be glad if anyone helps me improve this code.(Give suggestions on how to improve it).