Handling Mismatch Results

How do I handle past-the-end iterators returned by mismatch()?

When using std::ranges::mismatch(), it's important to handle past-the-end iterators properly to avoid dereferencing invalid iterators. std::ranges::mismatch() returns a pair of iterators, indicating where the first mismatch occurs.

If no mismatch is found, both iterators will be past-the-end iterators for their respective ranges. Here's an example demonstrating this:

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

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

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

  if (itA != A.end() && itB != B.end()) {
    std::cout << "First mismatch - A: " << *itA
              << ", B: " << *itB; 
  } else {
    std::cout << "No mismatch found,"
      " or one range is longer";
  }
}
First mismatch - A: 3, B: 4

If one of the ranges is longer, the past-the-end iterator indicates that the comparison reached the end of the shorter range without finding a mismatch. You can handle this scenario as follows:

#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";
  }

  if (itB != B.end()) {
    std::cout << "\nMismatch in B: " << *itB;
  }
}
Reached the end of A
Mismatch in B: 4

In this example, we check if itA is equal to A.end(), indicating we've reached the end of the first range. Similarly, we check if itB is not equal to B.end() to identify a mismatch in the second range.

Handling past-the-end iterators correctly ensures that your program doesn't attempt to access invalid memory, which can lead to undefined behavior or crashes. Always verify that iterators are within valid ranges before dereferencing them.

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()?
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