C++ Standard Library C++ STL Library

C++ <algorithm> - includes() Function



The C++ algorithm::includes function returns true if the sorted range [first1, last1) contains all elements of sorted range [first2, last2), else returns false.

In default version elements are compared using operator< and in custom version elements are compared using comp.

Syntax

//default version 
template <class InputIterator1, class InputIterator2r>
  bool includes (InputIterator1 first1, InputIterator1 last1,
                 InputIterator2 first2, InputIterator2 last2);

//custom version  
template <class InputIterator1, class InputIterator2, class Compare>
  bool includes (InputIterator1 first1, InputIterator1 last1,
                 InputIterator2 first2, InputIterator2 last2,
                 Compare comp);

Parameters

first1 Specify initial position of the input iterator1. The range used is [first1,last1).
last1 Specify final position of the input iterator1. The range used is [first1,last1).
first2 Specify initial position of the input iterator2. The range used is [first2,last2).
last2 Specify final position of the input iterator2. The range used is [first2,last2).
comp Specify a binary function that accepts two elements pointed by the iterators, and returns a value convertible to bool. The returned value indicates which element will go first.

Return Value

Returns true if the sorted range [first1, last1) contains all elements of sorted range [first2, last2), else returns false.

Time Complexity

Up to Linear i.e, Θ(n).

Example:

The example below shows the usage of algorithm::includes function.

#include <iostream>
#include <algorithm>
using namespace std;

int main (){
  int arr1[] = {10, 20, 30, 40, 50, 60, 70};
  int arr2[] = {20, 40, 60};
  int arr3[] = {25, 50, 75};

  cout<<boolalpha;

  //checking if arr1 contains all elements of arr2
  bool retval1 = includes(arr1, arr1+7, 
                          arr2, arr2+3);
  cout<<"Does arr1 include arr2: "<<retval1; 

  cout<<endl;
  //checking if arr1 contains all elements of arr3
  bool retval2 = includes(arr1, arr1+7, 
                          arr3, arr3+3);
  cout<<"Does arr1 include arr3: "<<retval2; 

  return 0;
}

The output of the above code will be:

Does arr1 include arr2: true
Does arr1 include arr3: false

❮ C++ <algorithm> Library