Comparison Algorithms

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

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.