Comparison Algorithms

Equal vs Is Permutation

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

Abstract art representing computer programming

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.

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

A computer programmer
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.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved