C++ Basics: Compare Sequences with Both End Iterators
Distinguish a differing element from a shorter matching prefix with std::mismatch.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as mismatch-length-safe-demo.cpp:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
const std::vector<int> expected{4, 8, 15};
const std::vector<std::vector<int>> cases{{4, 9, 15}, {4, 8}, {4, 8, 15}};
for (const auto& actual : cases) {
const auto [left, right] = std::mismatch(
expected.begin(), expected.end(), actual.begin(), actual.end());
if (left == expected.end() && right == actual.end()) {
std::cout << "Equal\n";
} else if (left == expected.end() || right == actual.end()) {
std::cout << "Length differs\n";
} else {
std::cout << "Mismatch at " << std::distance(expected.begin(), left) << '\n';
}
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic mismatch-length-safe-demo.cpp -o mismatch-length-safe-demo &&
./mismatch-length-safe-demoObserved output:
Mismatch at 1
Length differs
EqualRead the result
The first case differs at index 1. The second matches every available value but ends early. Only the third exhausts both ranges together. Testing both returned iterators separates those three useful diagnostics.
Apply it carefully
The four-iterator overload bounds both inputs. The older overload with only the second begin iterator assumes that the second range contains enough elements. Never dereference either returned iterator until you know it is not its corresponding end. A common prefix is not full equality when one input has additional elements.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- mismatch-length-safe-demo.cpp mismatch-length-safe-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.