#include <iostream>
#include <functional>
#include <list>
#include <iterator>
int reduce (std::list<int> l,std::function<int(int a,int b)> f,int start){
int sum=start;
for(auto i1=l.begin();i1!=l.end();++i1){
auto i2=++i1;
sum+=f((*i1),(*i2));
++i2;
}
return sum;
}
int main(){
std::list<int> list{11,4,5,12,6,8,9};
auto a=[](int a,int b){return a+b+1;};
int start=-12;
int o=reduce(list,a,start);
std::cout<<"Output: "<< o<<std::endl;
}
I have to write a reduce function that takes a list of integers as the first argument, second argument is a function that will reduce the elements of the container to one element and the third is initial value of the given accumulation (-12 in this example). It should reduce the elements of the passed container to 1 element using the function passed as an argument. The output should be 50.
When I write cout in for loop in order to see the output, iterators are returning elements which they should but why am I getting an inifite loop, is it because ++i2 line will come out of the container? What is the better way to write this code? How can I solve this problem so that second iterator doesn't reach outside of the container.What is your advice when it comes to iterating through list container? Thanks a lot
I think you are misunderstanding the task you have been asked to perform. This is my take
int reduce(std::list<int> l, std::function<int(int a,int b)> f, int start) {
for (auto it = l.begin(); it != l.end(); ++it) {
start = f(*it, start);
}
return start;
}
That's the normal mathematical definition of reduce