Comparison Algorithms

Handling Mismatch Results

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

Abstract art representing computer programming

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.

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