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.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the eight main comparison algorithms in the C++ Standard Library