C++ <algorithm> std::mismatch

The std::mismatch function in C++ is part of the <algorithm> header and is used to compare two sequences element by element, identifying the first position where the elements differ. It returns a pair of iterators pointing to the first mismatched elements in each sequence.


Syntax of std::mismatch

</>
Copy
template <class InputIterator1, class InputIterator2>
std::pair<InputIterator1, InputIterator2>
mismatch(InputIterator1 first1, InputIterator1 last1,
         InputIterator2 first2);

template <class InputIterator1, class InputIterator2, class BinaryPredicate>
std::pair<InputIterator1, InputIterator2>
mismatch(InputIterator1 first1, InputIterator1 last1,
         InputIterator2 first2, BinaryPredicate pred);

Parameters of std::mismatch

ParameterDescription
first1, last1Input iterators defining the range [first1, last1) for the first sequence.
first2Input iterator to the beginning of the second sequence. The function compares elements in the range starting from first2 up to the distance [first1, last1).
pred (optional)Binary predicate that takes two elements as arguments (one from each sequence) and returns a boolean indicating whether they are considered equal. If not provided, the function uses operator== by default.

Return Value of std::mismatch

The function returns a std::pair of iterators:

  • first: Iterator to the first element in the first sequence that does not match the corresponding element in the second sequence.
  • second: Iterator to the corresponding element in the second sequence.

If all elements match in the range, the function returns a pair with first set to last1 and second set to the element in the second sequence at the same relative position.


Examples for mismatch Function

Example 1: Finding the First Mismatch Between Two Arrays

In this example, we use std::mismatch to find the first differing elements between two arrays of integers.

Program

</>
Copy
#include <iostream>
#include <algorithm>
#include <utility>

int main() {
    int array1[] = {1, 2, 3, 4, 5};
    int array2[] = {1, 2, 0, 4, 5};

    auto result = std::mismatch(std::begin(array1), std::end(array1), std::begin(array2));

    if (result.first != std::end(array1)) {
        std::cout << "First mismatch found at position "
                  << std::distance(std::begin(array1), result.first) << ":\n";
        std::cout << "array1 contains " << *result.first << "\n";
        std::cout << "array2 contains " << *result.second << "\n";
    } else {
        std::cout << "No mismatches found; the sequences are equal.\n";
    }

    return 0;
}

Output

First mismatch found at position 2:
array1 contains 3
array2 contains 0

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <algorithm> for the std::mismatch function, and <utility> for the std::pair type.
  2. We define two arrays, array1 and array2, each containing five integers.
  3. We call std::mismatch, passing iterators to the beginning and end of array1, and the beginning of array2. The function compares corresponding elements from both arrays.
  4. The function returns a pair of iterators pointing to the first mismatched elements. We check if the first iterator is not equal to std::end(array1), indicating a mismatch was found.
  5. If a mismatch is found, we calculate its position using std::distance and print the differing elements from both arrays. If no mismatch is found, we print a message indicating the sequences are equal.

Example 2: Comparing Two Vectors with a Custom Predicate

In this example, we use std::mismatch with a custom predicate to compare two vectors of integers, considering elements equal if their absolute values are the same.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

bool abs_equal(int a, int b) {
    return std::abs(a) == std::abs(b);
}

int main() {
    std::vector<int> vec1 = {1, -2, 3, -4, 5};
    std::vector<int> vec2 = {1, 2, 3, 4, -5};

    auto result = std::mismatch(vec1.begin(), vec1.end(), vec2.begin(), abs_equal);

    if (result.first != vec1.end()) {
        std::cout << "First mismatch found at position "
                  << std::distance(vec1.begin(), result.first) << ":\n";
        std::cout << "vec1 contains " << *result.first << "\n";
        std::cout << "vec2 contains " << *result.second << "\n";
    } else {
        std::cout << "No mismatches found; the sequences are equal.\n";
    }

    return 0;
}

Output

No mismatches found; the sequences are equal.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, <algorithm> for the std::mismatch function, and <cmath> for the std::abs function.
  2. We define a custom predicate function abs_equal, which compares two integers based on their absolute values.
  3. We initialize two vectors vec1 and vec2, where corresponding elements in both vectors have the same absolute values.
  4. We call std::mismatch, passing the iterators of the two vectors and the custom predicate abs_equal.
  5. The function returns a pair of iterators pointing to the first mismatched elements. Since the sequences are considered equal based on the custom predicate, the iterators point to the end of their respective ranges.
  6. We check if the iterators point to the end of the range and print an appropriate message indicating no mismatches were found.

Examples for Exceptions Thrown by std::mismatch

The std::mismatch function can throw exceptions in the following scenarios:

  • If the comparison operation or the predicate (pred) throws an exception.
  • If an operation on the iterators, such as dereferencing or incrementing, throws an exception.

Example 1: Predicate Throws an Exception

This example demonstrates a case where the predicate function throws an exception during execution.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

bool faulty_predicate(int a, int b) {
    if (a < 0 || b < 0) {
        throw std::runtime_error("Negative value encountered during comparison.");
    }
    return a == b;
}

int main() {
    std::vector<int> vec1 = {1, -2, 3, 4, 5};
    std::vector<int> vec2 = {1, 2, 3, 4, -5};

    try {
        auto result = std::mismatch(vec1.begin(), vec1.end(), vec2.begin(), faulty_predicate);

        if (result.first != vec1.end()) {
            std::cout << "First mismatch found at position "
                      << std::distance(vec1.begin(), result.first) << ":\n";
            std::cout << "vec1 contains " << *result.first << "\n";
            std::cout << "vec2 contains " << *result.second << "\n";
        } else {
            std::cout << "No mismatches found; the sequences are equal.\n";
        }
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Negative value encountered during comparison.

Explanation

  1. We define a custom predicate faulty_predicate that throws a std::runtime_error if either of the input values is negative.
  2. We initialize two vectors vec1 and vec2, both containing some negative values.
  3. We call std::mismatch with the custom predicate. The function applies the predicate to corresponding elements from both vectors.
  4. When the predicate encounters a negative value, it throws an exception.
  5. The exception is caught in the try-catch block, and an error message is displayed.

Example 2: Iterator Throws an Exception

This example demonstrates a case where a custom iterator throws an exception during iteration.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FaultyIterator {
public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = int;
    using difference_type = std::ptrdiff_t;
    using pointer = const int*;
    using reference = const int&;

    FaultyIterator(const int* ptr, bool fail_after = false)
        : ptr(ptr), fail_after(fail_after), count(0) {}

    reference operator*() const {
        if (fail_after && count >= 2) {
            throw std::runtime_error("Iterator error during dereference.");
        }
        return *ptr;
    }

    FaultyIterator& operator++() {
        ++ptr;
        ++count;
        return *this;
    }

    bool operator!=(const FaultyIterator& other) const {
        return ptr != other.ptr;
    }

private:
    const int* ptr;
    bool fail_after;
    int count;
};

int main() {
    int arr1[] = {1, 2, 3, 4, 5};
    int arr2[] = {1, 2, 0, 4, 5};

    try {
        auto result = std::mismatch(
            FaultyIterator(arr1, true),
            FaultyIterator(arr1 + 5),
            FaultyIterator(arr2)
        );

        if (result.first != FaultyIterator(arr1 + 5)) {
            std::cout << "First mismatch found.\n";
        } else {
            std::cout << "No mismatches found; the sequences are equal.\n";
        }
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Iterator error during dereference.

Explanation

  1. We define a custom iterator FaultyIterator that throws a std::runtime_error after accessing two elements.
  2. We create two arrays, arr1 and arr2, for comparison.
  3. The std::mismatch function uses the custom iterator to compare the elements in both arrays.
  4. The custom iterator throws an exception during the third access, which is caught in the try-catch block, and an error message is displayed.