Signup/Sign In

Numeric Algorithms in C++ STL

Following are some Numeric algorithms in Standard Template library that we will be covering :

  • iota Method
  • accumulate Method
  • partial_sum Method

iota Method

This method assigns all the successive elements in range [first, last] as an incremented value of the element itself. It is available in c++ 11 and above. Its syntax is iota(iterator first, iterator last, int value ).

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

using namespace std;

int main()
{
    vector<int> v(10);
    /* now vector v is : 0,0,0,0,0,0,0,0,0,0  */
    
    iota(v.begin(), v.end(), 10 );
    
    /* now the vector v is 10,11,12,13,14,15,16,17,18,19  */
}

accumulate Method

This method performs the operation op on all the element in the range [first, last] and stores the result into the container result. There are two variations of accumulate, in the first one no binary operator is defined in the function call, so by default addition is performed, otherwise binary operator op is performed.

Following is the syntax of accumulate method with binary operator op:

accumulate(iterator first, iterator last, object_type result, binaryoperator op)

Following is an example to demonstrate the usage of accumulate :

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

using namespace std;

int myoperator(int a, int b )
{
    return a*b;
}

int main()
{
    vector<int> v;
    
    for(int i = 0 ; i < 10; i++) {
    v.push_back(i);
    }
    
    /* now vector v is : 0,1,2,3,4,5,6,7,8,9  */
    
    int result;
    
    accumulate(v.begin(), v.end(), result) ;
    
    /* as no operator is specified, accumulate add all the elements 
    between v.begin() and v.end() and store the sum in result */ 
    
    /* now result = 45 */
    
    accumulate(v.begin(), v.end(), result, myoperator) ;
    
    /* applies myoperator on all the elements in the range v.begin() and v.end() and store them in result */ 
    
    /* now result = 9!  */
}

partial_sum Method

This method assigns every element in the range starting from iterator result of the operation op on the successive range in [first, last]. Here binary_operation can be omitted, if there is no binary operator specified, addition is done by default.

The syntax of partial_sum is :

partial_sum(iterator first, iterator last, iterator result, binary_operation op)

Following is an example to demonstrate the usage of partial_sum :

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

using namespace std;

int myoperator(int a, int b)
{
    return a*b;
}

int main()
{
    int a[] = {1,2,3,4,5};
    vector<int> v (a,a+5);
    vector<int> v2;
    /* vector v is 1,2,3,4,5 */
    v2.resize(v.size());
    
    partial_sum(v.begin(), v.end(), v2.begin());
    
    /* now v2 is : 1,3,6,10,15 */
    /* sum of the successive range in v.begin() and v.end() */
    
    partial_sum(v.begin(), v.end(), v2.begin(), myoperator);
    
    /* now v2 is : 1,2,6,24,120 */
}