problem in template

Hi all.
This template is to add adjacent numbers, but my problem is that the output numbers that come out are "5 7 9 11 6" but I need the output to be with the following numbers "2 5 7 9 11". I hope someone can help me pls. Thnx.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <numeric>
#include <list>

using namespace std;

template <class in,class out> out plus_adj(in first,in last,out result)
{
  if (first!=last) {
    in prev =first;
    out result= prev;
    while (++first!=last ){
    in val = first;
      *result++ = (*val + *prev) ;
      prev = val;
    }
  }
  return result;
}

int main(){
    list<double> v{2,3,4,5,6};
    plus_adj(v.begin(),v.end(),v.begin());
    for(list<double>::iterator it=v.begin();it!=v.end();it++)
        cout<<*it<<" ";
    return 0;
}



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template < typename In, typename Out > Out plus_adj( In first, In last, Out result ) {

    if( first == last ) return result ;

    *result = *first ;
    In prev = first ;

    for( ++first, ++result ; first != last ; ++first, ++result ) {

        *result = *prev + *first ;
        prev = first ;
    }

    return result ;
}

http://coliru.stacked-crooked.com/a/c4cf8dfc5a3490ca

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template < typename In, typename Out > Out plus_adj( In first, In last, Out result ) {

    if( first == last ) return result ;

    *result = *first ;
    auto prev = *first ;

    for( ++first, ++result ; first != last ; ++first, ++result ) {

        const auto curr = *first ;
        *result = prev + curr ;
        prev = curr ;
    }

    return result ;
}

http://coliru.stacked-crooked.com/a/48e29b0406919064
Last edited on
Topic archived. No new replies allowed.