Comparing Different Length Ranges

How do I compare two ranges of different lengths using mismatch()?

std::ranges::mismatch() can be used to compare two ranges of different lengths by identifying where they start to differ.

If one range is shorter, mismatch() will return an iterator to the end of the shorter range and the corresponding position in the longer range where they start to differ. Here's an example:

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

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

  auto [itA, itB] = std::ranges::mismatch(A, B);

  if (itA == A.end()) {
    std::cout << "Reached the end of A\n";
  }

  if (itB != B.end()) {
    std::cout << "Mismatch in B at position "
      << std::distance(B.begin(), itB)
      << ": " << *itB;
  }
}
Reached the end of A
Mismatch in B at position 3: 4

This example demonstrates how to handle the case when the first range is shorter. itA will be A.end(), indicating that all elements of A were matched, while itB will point to the first unmatched element in B.

You can also handle the opposite case where the second range is shorter:

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

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

  auto [itA, itB] = std::ranges::mismatch(A, B);

  if (itB == B.end()) {
    std::cout << "Reached the end of B\n";
  }

  if (itA != A.end()) {
    std::cout << "Mismatch in A at position "
      << std::distance(A.begin(), itA)
      << ": " << *itA;
  }
}
Reached the end of B
Mismatch in A at position 3: 4

In this case, itB is B.end(), indicating that all elements of B were matched, while itA points to the first unmatched element in A.

When using std::ranges::mismatch() to compare ranges of different lengths, always check for past-the-end iterators before dereferencing them to avoid accessing invalid memory. This ensures your comparisons are safe and accurate.

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.

std::equal() vs std::is_permutation()
What is the difference between equal() and is_permutation()?
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()?
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