1

I saw this code in an old version of C++ Cookbook, and it mystifies me. This seems to compile, but I have no clue as to why the code would be written this way.

What does the T() mean? This is the init argument for std::accumulate -- the value to start the sum. I wrote a version where I put double() in place of T() (to "hardwire" the template), and it compiles. What does double() mean?

#include <iostream>
#include <numeric> // accumulate
#include <vector>

template<class T, class Iter_T>
void computeAccum(Iter_T first, Iter_T last, T& accum)
{
    accum = std::accumulate(first, last, T()); // Why is init argument equal to T()?
}

int main()
{
    std::vector<double> vd;
    vd.push_back(1.11);
    vd.push_back(2.22);
    vd.push_back(4.44);
    vd.push_back(3.33);
    double sum1;
    std::cout << "Here is the vector:" << std::endl;
    std::vector<double> ::iterator it;
    for (it = vd.begin(); it != vd.end(); ++it) {
        std::cout << *it << std::endl;
    }

    computeAccum2(vd.begin(), vd.end(), sum1);
    std::cout << "Answer: " << sum1 << std::endl;
}
Anthony Mannucci
  • 277
  • 2
  • 12

2 Answers2

2

There are three arguments to this variant of the accumulator, the first and last elements in the range, and the initial value to start with (this particular prototype below is the C++20 one though earlier ones are similar, just with less constexpr goodness):

template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );

It allows you to accumulate to something that's already been started. So if you accumulated the values 3 and 4, with an initial value of 22, the final value would be 28. The reason for this is because you may want to accumulate a certain set of data then later accumulate more. By using an initial starting value, you can do multiple accumulations into a single item.

In this case, T() is simply the default-constructed initial element of the template type, basically a "zero" value for whatever type you're using.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

It's basically zero initialization. Consider this example for clarification

#include <bits/stdc++.h> 
using namespace std;

int main(){
    cout<<"Int: "<<int()<<endl;
    cout<<"Float: "<<float()<<endl;
    cout<<"String: "<<string();
}

Output:

Int: 0
Float: 0
String: 
Ajay Dabas
  • 1,404
  • 1
  • 5
  • 15