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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Custom Comparison for std::equal()
How do I customize the comparison behavior for equal()?
Handling Mismatch Results
How do I handle past-the-end iterators returned by mismatch()?
Equal vs Lexicographical Compare
When should I use lexicographical_compare() over equal()?
Applications of is_permutation()
What are some practical applications of is_permutation()?
Comparing Different Length Ranges
How do I compare two ranges of different lengths using mismatch()?
Understanding Identity Permutations
What are identity permutations and why are they important?
Comparing Floating Point Numbers
How do I compare ranges that contain floating-point numbers?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant