Comparison Algorithms

# 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.

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

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

This Question is from the Lesson:

### Comparison Algorithms

An introduction to the eight main comparison algorithms in the C++ Standard Library

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.