×

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

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.

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...

3 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

Copy elision in C++

The Copy Omission is another name for the Copy Elision. One of the several compiler optimization techniques is copy elision. It prevents items from being copied inadvertently. This Copy Elision approach...

3 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.