Array algorithms in C++ STL


Since C++11 there are different functions added into the STL. These functions are present at algorithm header file. Here we will see some functions of this.

  • The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea

Example

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(all_of(arr, arr + n, [](int x){return x%2 == 0;})) {
      cout << "All are even";
   } else {
      cout << "All are not even";
   }
}

Output

All are even


  • The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea.

Example

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(any_of(arr, arr + n, [](int x){return x%2 == 1;})) {
      cout << "At least one element is odd";
   } else {
      cout << "No odd elements are found";
   }
}

Output

At least one element is odd


  • The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea.

Example

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(none_of(arr, arr + n, [](int x){return x < 0 == 1;})) {
      cout << "All elements are positive";
   } else {
      cout << "Some elements are negative";
   }
}

Output

All elements are positive


  • The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea.

Example

#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   int arr2[n];
   copy_n(arr, n, arr2);
   for(int i = 0; i < n; i++) {
      cout << arr2[i] << " ";
   }
}

Output

2 4 6 8 10 5 62


  • The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value.

Example

#include <iostream>
#include <numeric>
using namespace std;
main() {
   int n = 10;
   int arr[n];
   iota(arr, arr+n, 10);
   for(int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
}

Output

10 11 12 13 14 15 16 17 18 19

Updated on: 20-Aug-2019

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements