How to use is_permutation() function in C++

The is_permutation() function in C++ helps determine whether two sequences are permutations of each other. In other words, this function discerns whether all the elements in the two sequences are the same, even if they are in a different order. This function is available in the <algorithm.h> header file.

Syntax

bool is_permutation(ForwardIterator1 first_one, ForwardIterator1 last_one, ForwardIterator2 first_two)

The is_permutation() function accepts the following parameters:

  • first_one: This is an iterator that points to the start position of the first sequence.

  • last_one: This is an iterator that points to the last position of the first sequence.

  • first_two: This is an iterator that points to the first position of the second sequence.

Return

The is_permutation() function returns a boolean value, where true indicates that all the elements in both the sequences are the same and false indicates that the elements are different.

Code

Let’s look at the code below:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
vector<int> seq_one = {1,2,3,4,5};
vector<int> seq_two = {3,1,4,5,2};
if(is_permutation(seq_one.begin(), seq_one.end(), seq_two.begin()))
cout << "Two Sequences contain the same elements.";
else
cout << "Two Sequences contains different elements.";
return 0;
}

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In lines 7 and 8, we create the two sequences.
  • In line 10, we call the is_permutation() function and pass all required parameters.
  • In lines 11 and 13, we print the result accordingly.

This way, we can easily check whether two sequences are a permutation of each other.

Free Resources