C++

# Summing Vector Elements in C++

The obvious way to sum the elements of a vector is to add them one-by-one beginning from the first. In fact, there is no other way, which has an advantage over this, everything being equal. And so the classic for-loop can be used to sum up the elements of a vector; the range-based for-statement can be used to sum up the elements of a vector; the for_each() function included from the algorithm library can be used to sum up the elements of a vector; the accumulate() function included from the numeric library can be used to sum up the elements of a vector.

With the first three methods mentioned above, statements have to be written to actually do the summing. With the accumulate method, the accumulate() function does the summing without additional summing statements. These four methods are illustrated in this article. In order to code a vector in a C++ program, the vector library as to be included into the program.

Article Content

– Adding Vector Elements using the for-loop

– Adding Vector Elements using the Range-Based for-statement

– Adding Vector Elements using the for_each() Function

– Adding Vector Elements using the accumulate() function

– Conclusion

## Adding Vector Elements Using the For-Loop

Consider the vector:

vector<float> vtr = {1.1, 2.2, 3.3, 4.4, 5.5};

In order to add all these elements from the beginning, a sum variable, initially holding the value of zero, has to be declared as follows:

float sum = 0.0;

From index zero to the last index, each value is added to sum in a for-loop. The following program illustrates this:

#include <iostream>

#include <vector>

using namespace std;
int main()
{
vectorvtr = {1.1, 2.2, 3.3, 4.4, 5.5};
float sum = 0.0;

for (int i=0; i<vtr.size(); i++)
sum += vtr[i];
cout<< sum <<endl;

return 0;
}

The output is 16.5 as expected. Notice that the vector library was included, and the standard namespace was used.

## Adding Vector Elements Using the Range-Based For-Statement

Consider the following vector of integers:

vector<int> vtr = {1, 2, 3, 4, 5};

In order to add all these elements from the beginning, a sum variable, initially holding the value of zero, has to be declared as follows:

int sum = 0;

From the first element of the vector to the last element, each value is added to sum in the range-based for-loop. The range-based for-compound statement is similar to the for-compound statement above. However, the parameters of the range-based for-loop are different from the those of the classic for-loop (above).

There are two parameters in the parentheses of the range-based for-loop: the first one is a variable declaration that refers to the next element in the vector, beginning from the first. It replaces vtr[i], of the classic for-loop above. The second parameter is the name of the vector. The syntax of the range-based for-compound statement, is

for ( init-statement-optional for-range-declaration : for-range-initializer ) statement

The range-based for-loop is a variant of the classic for-loop; it is more convenient to use in iterating over lists. The variable declaration is before the colon, and the name of the vector is after the colon. The following program shows the range-based for-compound statement in action:

#include <iostream>

#include <vector>

using namespace std;
int main()
{
vectorvtr = {1, 2, 3, 4, 5};
int sum = 0;

for (int var :vtr)
sum += var;
cout<< sum <<endl;

return 0;
}

The output is 15. Note: the name of the variable, var, is the choice of the programmer. In that position, it refers to the next element (value) in the vector.

## Adding Vector Elements Using the for_each() Function

The for_each() function is in the algorithm library. The syntax is:

template<class InputIterator, class Function>

constexpr Function for_each(InputIterator first, InputIterator last, Function f);

The first argument is an iterator that points to the start (first element) of the vector. The second argument is an iterator that points to the end (just after the last element) of the same vector. The third argument is just the name of the function that has the code to do the summing. This function is a function object.

The for_each() function is used as a function call, which will send each element of the vector, beginning from the first to another function, f. The function, f will do anything it wants to do with the element in its function body. Each element of the vector is an argument to the function, f. The programmer defines the function, f and can give it the name other than f(). The parameter of this function has to be of the type of each of the vector elements (all vector elements are of the same type). The name of the parameter is the programmer’s choice. So, the for_each() function calls the function, f() for each vector element.

The program to use the for_each() function should begin as follows:

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

vector<int> vtr = {1, 2, 3, 4, 5};

int sum = 0;

The vector and algorithm libraries are included. The initialized vector and the initialized sum of zero are declared. A good summing function definition for f, which follows in the program, can be:

void fn (int var) {

sum += var;

}

Each time the function, fn is called by the for_each() function, the next value of the vector is added to sum. The C++ main function can be as follows:

int main()

{

for_each(vtr.begin(), vtr.end(), fn);

cout << sum << endl;

return 0;

}

The for_each() function is called once from the algorithm library. Its first argument is an iterator that points to the beginning of the vector; second argument points to the end of the vector; and third argument is the name of the function object, that is called for each element in the vector. After the number of calls, which correspond to the number of vector elements, have been made, the next statement in the main function, prints out the final sum.

## Adding Vector Elements Using the accumulate() Function

The syntax of the accumulate() function of the numeric library, is:

template<class InputIterator, class T>

constexpr T accumulate(InputIterator first, InputIterator last, T init);

With this function, there is no need for the programmer to write code (statements) for summing. The accumulate() function does the summing. Its first argument is an iterator pointing to the beginning of the vector. Its second argument is an iterator, pointing to the end of the vector. Its last argument is the initial sum value. It should be zero for a vector of ints, and 0.0 for a vector of floats (or doubles). The function returns the sum.

### Vector of Integers

The following program sums all the elements of a vector of integers:

#include <iostream>

#include <vector>

#include <numeric>

using namespace std;

int main()
{
vectorvtr = {1, 2, 3, 4, 5};

int sum = accumulate(vtr.begin(), vtr.end(), 0);

cout<< sum <<endl;
return 0;
}

The output is 15; correct!

### Vector of Floats

The following program sums all the elements of a vector of floats:

#include <iostream>

#include <vector>

#include <numeric>

using namespace std;

int main()
{
vectorvtr = {1.1, 2.2, 3.3, 4.4, 5.5};

float sum = accumulate(vtr.begin(), vtr.end(), 0.0);

cout<< sum <<endl;
return 0;
}

The output is 16.5; correct!

### Problem with the Accumulate Function

If the third argument of the accumulate function is the wrong type, then the sum would be wrong. For example, if the elements are floats, and the third argument is 0 (integer), then the sum would ignore all the decimal parts of the values to have an int sum. The following program illustrates this:

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main()
{
vectorvtr = {1.1, 2.2, 3.3, 4.4, 5.5};

float sum = accumulate(vtr.begin(), vtr.end(), 0);

cout<< sum <<endl;
return 0;
}

The output is 15; wrong!

## Conclusion

The classic for-loop can be used to sum up the elements of a vector. The range-based for-statement can be used to sum up the elements of a vector. The for_each() function included from the algorithm library can be used to sum up the elements of a vector. The accumulate() function included from the numeric library can be used to sum up the elements of a vector. Just watch out for incorrect use of its third argument. 