×

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric header's functions include the following:

  • Iota
  • Accumulate
  • Reduce
  • Inner_product
  • Partial _ sum etc.

This article describes the numeric header functions accumulate() and partial sum(), which can be used to expedite and simplify competitive programming.

1. accumulate ()

With the variable sum, this function returns the total of all values falling inside the range [first, last]. We often use a linear operation to calculate the sum of the items in a certain range or an entire array. This entails adding each element in the range individually and saving the result in a variable after each iteration.

Syntax:

Accumulate (first, last, sum)

Or

Accumulate (first, last, sum, myfun);

Parameters

  • first, last: It specifiesstart and end components of the range to which elements are being added.
  • sum: It specifiesstarting point of the total
  • myfun: It specifiesa method for carrying out any certain operation.

For instance, we can determine the combination of the first and last element.

Example:

#include <iostream>
#include <numeric>
usingnamespace std;
intmyfun(int x, int y)
{
    // combination of two adjacent numbers are taken
    return x * y;
}
 
int main()
{
    // Initial sum = 1
    int sum = 1;
    inta[] = { 5, 10, 15 };
 
    cout<< "\nResult using accumulate: ";
    cout<<accumulate(a, a + 3, sum);
 
    //with the help of accumulatefunction with
    // function def
    cout<< "\nResult using accumulate with"
            "user-defined function: ";
    cout<< accumulate(a, a + 3, sum, myfun);
 
    // with the help of accumulate function with
    // functionpre-defined
    cout<< "\nResult using accumulate with "
            "pre-defined function: ";
    cout<<accumulate (a, a + 3, sum, std::minus<int>());
 
    return0;
}

Output:

Sum of all elements between k1th and k2th smallest elements

Given two numbers, k1 and k2, and an array of integers Find the total number of elements in the array between the two provided smallest elements, k1 and k2. One may suppose that all of the array's elements are distinct and that (1 = k1 k2 = n).

Sorting:

#include <bits/stdc++.h>
 
usingnamespacestd;
 


intsumBetweenTwoKth (intarr [], intn, intk1, intk2)
{
    
    sort (arr, arr + n);
 
    
     int result = 0;
     for (int i=k1; i<k2-1; i++)
      result += arr[i]; */
    returnaccumulate (arr + k1, arr + k2 - 1, 0);
}
 


intmain ()
{
    intarr[] = {20, 8, 22, 4, 12, 10, 14 };
    intk1 = 3, k2 = 6;
    intn = sizeof(arr) / sizeof (arr[0]);
    cout<<sumBetweenTwoKth(arr, n, k1, k2);
    return0;
}

Output:

The outcome obtained is 26

2. partial_sum ()

Each point of the second array is given a partial sum of the corresponding elements of an array by this function. It returns and keeps in another array b the partial sum of each set of values falling between [first, last].

For instance, the ys can be calculated as follows if x represents an element in [first, last] and y represents an element in the outcome:

Y0 = x0
Y1 = x0 + x1
Y2 = x0 + x1 + x2
Y3 = x0 + x1 + x2 + x3
Y4 = x0 + x1 + x2 + x3 + x4

Syntax:

Partial _ sum (first, last, b);

Or

partial _ sum (first, last, b, myfun);

Parameters:

  • first, last: range's start and last components to which more elements are to be appended.
  • b: index of the array containing the corresponding partial sum.
  • myfun: a function established by the user to carry out any task.

Example:

#include <iostream>
#include <numeric>
usingnamespacestd;
 


intmyfun (intx, inty)
{
   
  
    returnx + 2 * y;
}
 
intmain ()
{
    inta [] = {1, 2, 3, 4, 5 };
    intb [5];
 
    
    partial_sum(a, a + 5, b);
 
    cout<< "Partial Sum - Using Default function: ";
    for(inti = 0; i< 5; i++)
        cout<< b[i] << ' ';
    cout<< '\n';
 
    
    partial_sum(a, a + 5, b, myfun);
 
    cout<< "Partial sum - Using user defined function: ";
    for(inti = 0; i< 5; i++)
        cout<< b[i] << ' ';
    cout<< '\n';
 
    return0;
}

Output:

Adding partially – with the help of attribute default: 1 3 6 10 15
Adding partially_ with the help of user defined attribute: 1 5 11 19 29


Y00 = x0 
y1 = x0 + x1 
y2 = x0 + x1 + x2 
y3 = x0 + x1 + x2 + x3 
y4 = x0 + x1 + x2 + x3 + x4

Related Topics

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.