includes() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). includes() is a method in the STL that tests whether a sorted range includes another sorted range.

Syntax:

includes( iterator_begin1, iterator_end1, iterator_begin2, iterator_end2, comparator); //comparator is optional

Parameters: The includes() method accepts 5 parameters

  • iterator_begin1, iterator_end1: Iterator to the initial and final position of first sorted sequence ( Note: the range is [iterator_begin1, iterator_end1) )
  • iterator_begin2, iterator_end2: Iterator to the initial and final position of second sorted sequence ( Note: the range is [iterator_begin2, iterator_end2) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: true if second range is included in the first range, false otherwise

Example of includes() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main () {

  vector<int> v1;
  v1.push_back(5);
  v1.push_back(6);
  v1.push_back(3);
  v1.push_back(1);
  v1.push_back(2);

  vector<int> v2;
  v2.push_back(3);
  v2.push_back(1);
  v2.push_back(2);

  sort (v1.begin(),v1.end());   // 1 2 3 5 6
  sort (v2.begin(),v2.end());   // 1 2 3

  if(includes(v1.begin(), v1.end(), v2.begin(), v2.end()))
    cout<<"V1 includes V2";

}

Output:

V1 includes V2

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top