std::equal()
vs std::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.
Comparison Algorithms
An introduction to the eight main comparison algorithms in the C++ Standard Library