The is_permutation function in C++ Algorithm compares the elements within two containers. It returns true if all elements in both containers match, even if they are in a different order. The function operates on the range [first1, last1) for the first container and starts from first2 for the second container.
Syntax
template<class ForwardIterator1, class ForwardIterator2> bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);
template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator first2, BinaryPredicate pred);
Parameter
It serves as an input iterator pointing to the initial element within the range of [first1, last1).
It serves as an input iterator pointing to the final element within the range from the initial element to the element before the last one.
It serves as an input iterator pointing to the initial element within the [first2, last2) range.
pred : It is a binary operation that takes two elements as parameters and executes the specified task.
Return value
The function will output true if all elements in both containers match, even if they are in a different order; otherwise, it will return false.
Example
#include<iostream>
#include<algorithm>
#include<array>
int main()
{
std::array<int, 5> a={6,7,8,9,10};
std::array<int, 5> b={10,8,7,6,9};
if(std::is_permutation(a.begin(),a.end(),b.begin()))
std::cout<<"a and b have same elements.\n";
return 0;
}
Output:
a and b have same elements.
Complexity
The function exhibits a linear time complexity from the initial element to the final element.
Data races
Objects in both ranges are accessed.
Exceptions
The function will raise an exception if any of the arguments also raises an exception.