Firstly you cannot apply std::transform
or similar STL functions on containers
with different types like here we have vector
of both string
& int
type. You need to have both either string or int to apply STL. Assuming both your vectors are of int
type (forgive me for that but I m just showing how your operation can take place) :-
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v {1,2,3,4,5,6};
vector<int> result(v.size());
int i=0;
adjacent_difference (v.begin(), v.end(), result.begin(),[&i](int s1, int s2)
{
int sum=0;
if (i%2==0)
sum=s1+s2;
++i;
return sum;
});
auto it = partition (result.begin(), result.end(), [](int x)
{
return (x!=0);
});
int pos=it-result.begin()-1;
result.erase (it, result.end());
result.erase (result.begin());
result.resize(pos);
for_each (result.begin(), result.end(), [](int x)
{
cout<<x<<' ';
});
return 0;
}
Output will be :-
3 7 11
Here std::adjacent_difference
will calculate the adjacent sums according to the function I have provided. For i=0, 2, 4, 2n, it will calculate the sum, else it will return 0. However the first element is always copied as it is, hence here first element in result
will be 1.
std::partition
is used to separate non-zero numbers with 0 (just a logic, you can use yours) as for i=2n+1, 0 was returned to result
. This return an iterator
to the element which is the last in the partition condition (here the last non-zero number e after which 0 starts).
Now as we have separated 0 & non-zero numbers, we need to remove the undesired ones. Hence you get 2 erase
functions: One to eliminate 0 & the other to eliminate 1 in the beginning. After removing we resize the result vector & iterate over it.
HOWEVER, according to your case, a for loop
is the best !!!