While solving many coding problems, we encounter the need to calculate the adjacent difference of every element in the array. For instance, in many problems, you have to calculate the prefix sum of the array.
For example, if we have the following array:
Then the adjacent difference will be:
In other words, we keep the first element as it is, but then we calculate the difference between the next element and the current element.
In coding contests, we usually do not have much time to write these simple logics. This is where we can use the adjacent_difference()
function. This function calculates the adjacent differences.
The adjacent_difference()
function accepts the parameters given below:
first
: This parameter specifies the index of the array or vector from where you want to start your search.
last
: This parameter specifies the index of the array or vector where you want to end your search.
result
: This parameter points to the initial address of the array or vector where the difference will be stored. The size of the array or vector should be large enough to store the differences within the range [first, last), i.e., there should be enough free memory available to store the result. It does not matter what size you specify for the result
array.
operation
: This is an optional parameter that can help you customize the difference. For example, instead of the adjacent difference of elements, you can calculate the adjacent sum of the elements. This parameter specifies a binary function that accepts two elements of the same type that you have in your array or vector, and then returns the result of the same type.
The adjacent_difference()
function returns a pointer that points past the last element stored in the result
.
Let’s have a look at the code now.
#include <iostream>#include <numeric>using namespace std;int main() {int val[] = {1,2,3,5,9,11,12};int result[7];adjacent_difference(val, val+7, result);for (int i = 0; i < 7; i++)cout << result[i] << ' ';return 0;}
adjacent_difference()
function.result
array.Now, let’s have a look at the usage of the optional parameter condition
in the following code snippet.
#include <iostream>#include <numeric>using namespace std;int prefix_sum(int a, int b){return a + b;}int main() {int val[] = {1,2,3,5,9,11,12};int result[7];adjacent_difference(val, val+7, result, prefix_sum);for (int i = 0; i < 7; i++)cout << result[i] << ' ';return 0;}
adjacent_difference()
function to calculate the adjacent sum of two numbers instead of calculating the difference of two numbers.Here, we actually implemented the prefix sum logic with the
adjacent_difference()
function.
In this way, we can skip writing simple logics, and use this function to save time and effort.