Comparison Algorithms

# Equal vs Is Permutation

## What is the difference between equal() and is_permutation()?

The main difference between std::ranges::equal() and std::ranges::is_permutation() lies in how they compareÂ collections.

std::ranges::equal() checks if two collections have the same elements in the same order. If any element differs or is out of order, the function returns false. ForÂ example:

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

int main() {
std::vector<int> A{1, 2, 3};
std::vector<int> B{1, 2, 3};

if (std::ranges::equal(A, B)) {
std::cout << "Ranges are equal";
} else {
std::cout << "Ranges are not equal";
}
}
Ranges are equal

In this case, std::ranges::equal() returns true because both collections contain the same elements in the sameÂ order.

On the other hand, std::ranges::is_permutation() checks if two collections contain the same elements, regardless of order. This means that even if the elements are shuffled, the function will return true if all elementsÂ match:

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

int main() {
std::vector<int> A{1, 2, 3};
std::vector<int> B{3, 2, 1};

if (std::ranges::is_permutation(A, B)) {
std::cout << "Ranges are a permutation";
} else {
std::cout << "Ranges are not a permutation";
}
}
Ranges are a permutation

Here, std::ranges::is_permutation() returns true because both collections contain the same elements, even though they are in a differentÂ order.

ToÂ summarize:

• Use std::ranges::equal() when the order of elements matters.
• Use std::ranges::is_permutation() when the order of elements does not matter, and you only care about the presence of the same elements.

These functions are useful in different scenarios depending on whether the sequence of elements is important for yourÂ application.

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

Part of the course:

## Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

### This course includes:

• 124 Lessons
• 550+ Code Samples
• 96% Positive Reviews
• Regularly Updated
• Help and FAQ
Free, Unlimited Access

### Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.