@specsoftdev live:.cid.8e17e9b93cabb607 specsoftdev@gmail.com
std::ranges::mismatch
Актуально для C++26.

#include <algorithm>
Актуально на 2025-05-31.


Define overload #1
template<input_iterator I1, sentinel_for<I1> S1,
         input_iterator I2, sentinel_for<I2> S2,
         class Pred = ranges::equal_to,
         class Proj1 = identity,
         class Proj2 = identity>
requires indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr ranges::mismatch_result<I1, I2>
    mismatch(I1 first1, S1 last1, I2 first2, S2 last2,
             Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {});

Вычисляет первое расхождение двух диапазонов [first1, last1] и [first2, last2].
Example, possible implementation
Define overload #2
template<input_range R1, input_range R2,
         class Pred = ranges::equal_to,
         class Proj1 = identity,
         class Proj2 = identity>
requires indirectly_comparable<iterator_t<R1>, iterator_t<R2>, Pred, Proj1, Proj2>
constexpr ranges::mismatch_result<borrowed_iterator_t<R1>, borrowed_iterator_t<R2>>
    mismatch(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {});

Вычисляет первое расхождение двух диапазонов "r1" и "r2".
Example, possible implementation

Возвращаемое значение

Вернёт пару итераторов { first1 + n, first2 + n }, где n, количество эквивалентных элементов.




Сложность

Линейная =  min(last1 - first1, last2 - first2).



Examples


Example 1:
#include <iostream>
#include <algorithm>
#include <ranges>
#include <array>
#include <string_view>
namespace ranges = std::ranges;


template<class ...T>
constexpr
auto mismatch_test(T&& ...haystack)
{
    using RT = std::common_type_t<T...>;
    auto compute = [](auto haystack) {
        auto result = ranges::mismatch(haystack, haystack | std::views::reverse);
        return RT{haystack.cbegin(), result.in1};
    };
    return std::array<RT, sizeof ...(T)>
    {
        compute(haystack)...
    };
}


template<class T, std::size_t ...I>
void print_array(const T& array, std::index_sequence<I...>)
{
    ((std::cout << (I+1) << ": " << array[I] << '\n'), ...);
}


template<class T, std::size_t N>
constexpr
void print_array(const std::array<T, N>& array)
{
    print_array(array, std::make_index_sequence<N>{});
}


int main()
{
    using namespace std::string_view_literals;
    auto array = mismatch_test("level"sv,
                           "abcdfba"sv,
                           "lived devil"sv,
                           "another"sv);
    print_array(array);
}



1: level
2: ab
3: lived devil
4:






Changelog

C++20
Введён в стандарт.


See also

TODO

This page was last modified on 2025-05-31