std::equal(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

okay bestie, welcome to std::equal(3) from the C++ Standard Libary β€” yes, β€œLibary,” that's what the header says, and we're not fixing it πŸ’…. This is part 1 of 2, so hydrate and stay tuned, because we're about to make iterator ranges feel like a group chat.

🌸 NAME 🌸

std::equal - std::equal

That's it. That's the name section. She said what she said, and honestly? Iconic. πŸŽ€


✨ Synopsis ✨

Defined in header <algorithm> πŸ¦‹

Okay so here's the whole overload lineup, and yes, we're doing all eight. No skipping. Not me being normal about templates.

Overload (1) β€” (constexpr since C++20)

template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2 );

Overload (2) β€” (since C++17)

template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
bool equal( ExecutionPolicy&& policy,
            ForwardIt1 first1, ForwardIt1 last1,
            ForwardIt2 first2 );

Overload (3) β€” (constexpr since C++20)

template< class InputIt1, class InputIt2, class BinaryPred >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2, BinaryPred p );

Overload (4) β€” (since C++17)

template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPred >
bool equal( ExecutionPolicy&& policy,
            ForwardIt1 first1, ForwardIt1 last1,
            ForwardIt2 first2, BinaryPred p );

Overload (5) β€” (since C++14), (constexpr since C++20)

template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2, InputIt2 last2 );

Overload (6) β€” (since C++17)

template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >
bool equal( ExecutionPolicy&& policy,
            ForwardIt1 first1, ForwardIt1 last1,
            ForwardIt2 first2, ForwardIt2 last2 );

Overload (7) β€” (since C++14), (constexpr since C++20)

template< class InputIt1, class InputIt2, class BinaryPred >
bool equal( InputIt1 first1, InputIt1 last1,
            InputIt2 first2, InputIt2 last2, BinaryPred p );

Overload (8) β€” (since C++17)

template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class BinaryPred >
bool equal( ExecutionPolicy&& policy,
            ForwardIt1 first1, ForwardIt1 last1,
            ForwardIt2 first2, ForwardIt2 last2,
            BinaryPred p );

So what does it actually do? Checks whether [first1, last1) and a range starting from first2 are equal πŸ‘€:

  • For overloads (1-4), the second range has std::distance(first1, last1) elements.
  • For overloads (5-8), the second range is [first2, last2).

And the comparison tea β˜•:

  • 1,5) Elements are compared using operator==.
  • 3,7) Elements are compared using the given binary predicate p.
  • 2,4,6,8) Same as (1,3,5,7), but executed according to policy.

These overloads participate in overload resolution only if:

  • until C++20: std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> is true.
  • since C++20: std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> is true.
lowkey important: those execution-policy overloads are cute but picky. The std::is_execution_policy_v condition is not a vibe suggestion, it's literally the participation rule. πŸ’…

πŸŽ€ Parameters πŸŽ€

  • first1, last1 β€” the first range of the elements to compare.
  • first2, last2 β€” the second range of the elements to compare.
  • policy β€” the execution policy to use. See execution policy for details.
  • p β€” binary predicate which returns true if the elements should be treated as equal.

The signature of the predicate function should be equivalent to the following:

bool pred(const Type1 &a, const Type2 &b);

While the signature does not need to have const &, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1 & is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy (since C++11)).

The types Type1 and Type2 must be such that objects of types InputIt1 and InputIt2 can be dereferenced and then implicitly converted to Type1 and Type2 respectively.


πŸ¦‹ Type requirements πŸ¦‹

  • InputIt1, InputIt2 must meet the requirements of LegacyInputIterator.
  • ForwardIt1, ForwardIt2 must meet the requirements of LegacyForwardIterator.
  • BinaryPred must meet the requirements of BinaryPredicate.

πŸ‘‘ Return value πŸ‘‘

  • 1-4) If each corresponding elements in the two ranges are equal, returns true. Otherwise returns false.
  • 5-8) If std::distance(first1, last1) and std::distance(first2, last2) are equal, and each corresponding elements in the two ranges are equal, returns true. Otherwise returns false.

🌈 Complexity 🌈

Given N_1 as std::distance(first1, last1) and N_2 as std::distance(first2, last2):

  • 1) At most N_1 comparisons using operator==.
  • 2) O(N_1) comparisons using operator==.
  • 3) At most N_1 applications of the predicate p.
  • 4) O(N_1) applications of the predicate p.
  • 5-8) If InputIt1 and InputIt2 are both LegacyRandomAccessIterator, and last1 - first1 != last2 - first2 is true, no comparison will be made.

Otherwise, given N as min(N_1,N_2):

  • 5) At most N comparisons using operator==.
  • 6) O(N) comparisons using operator==.
  • 7) At most N applications of the predicate p.
  • 8) O(N) applications of the predicate p.

πŸ”₯ Exceptions πŸ”₯

The overloads with a template parameter named ExecutionPolicy report errors as follows:

  • If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is called. For any other ExecutionPolicy, the behavior is implementation-defined.
  • If the algorithm fails to allocate memory, std::bad_alloc is thrown.

πŸ’– POSSIBLE IMPLEMENTATION πŸ’–

okay so bestie, here's the possible implementation tea β˜• β€” this is the vibe for overloads (1), (3), (5), and (7). Copy these exactly, including the details::equal calls β€” no autocorrect, no cap πŸ’€βœ¨

equal (1)

template<class InputIt1, class InputIt2>
constexpr //< since C++20
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2)
{
    for (; first1 != last1; ++first1, ++first2)
        if (!(*first1 == *first2))
            return false;

    return true;
}

equal (3)

template<class InputIt1, class InputIt2, class BinaryPred>
constexpr //< since C++20
bool equal(InputIt1 first1, InputIt1 last1,
           InputIt2 first2, BinaryPred p)
{
    for (; first1 != last1; ++first1, ++first2)
        if (!p(*first1, *first2))
            return false;

    return true;
}

equal (5)

namespace detail
{
    // random-access iterator implementation (allows quick range size detection)
    template<class RandomIt1, class RandomIt2>
    constexpr //< since C++20
    bool equal(RandomIt1 first1, RandomIt1 last1, RandomIt2 first2,
               RandomIt2 last2,
               std::random_access_iterator_tag,
               std::random_access_iterator_tag)
    {
        if (last1 - first1 != last2 - first2)
            return false;

        for (; first1 != last1; ++first1, ++first2)
            if (!(*first1 == *first2))
                return false;

        return true;
    }

    // input iterator implementation (needs to manually compare with β€œlast2”)
    template<class InputIt1, class InputIt2>
    constexpr //< since C++20
    bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2,
               InputIt2 last2,
               std::input_iterator_tag, std::input_iterator_tag)
    {
        for (; first1 != last1 && first2 != last2; ++first1, ++first2)
            if (!(*first1 == *first2))
                return false;

        return first1 == last1 && first2 == last2;
    }
}

template<class InputIt1, class InputIt2>
constexpr //< since C++20
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2)
{
    details::equal(first1, last1, first2, last2,
                   typename std::iterator_traits<InputIt1>::iterator_category(),
                   typename std::iterator_traits<InputIt2>::iterator_category());
}

equal (7)

namespace detail
{
    // random-access iterator implementation (allows quick range size detection)
    template<class RandomIt1, class RandomIt2, class BinaryPred>
    constexpr //< since C++20
    bool equal(RandomIt1 first1, RandomIt1 last1,
               RandomIt2 first2, RandomIt2 last2, BinaryPred p,
               std::random_access_iterator_tag,
               std::random_access_iterator_tag)
    {
        if (last1 - first1 != last2 - first2)
            return false;

        for (; first1 != last1; ++first1, ++first2)
            if (!p(*first1, *first2))
                return false;

        return true;
    }

    // input iterator implementation (needs to manually compare with β€œlast2”)
    template<class InputIt1, class InputIt2, class BinaryPred>
    constexpr //< since C++20
    bool equal(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2, BinaryPred p,
               std::input_iterator_tag, std::input_iterator_tag)
    {
        for (; first1 != last1 && first2 != last2; ++first1, ++first2)
            if (!p(*first1, *first2))
                return false;

        return first1 == last1 && first2 == last2;
    }
}

template<class InputIt1, class InputIt2, class BinaryPred>
constexpr //< since C++20
bool equal(InputIt1 first1, InputIt1 last1,
           InputIt2 first2, InputIt2 last2, BinaryPred p)
{
    details::equal(first1, last1, first2, last2, p,
                   typename std::iterator_traits<InputIt1>::iterator_category(),
                   typename std::iterator_traits<InputIt2>::iterator_category());
}

🌸 NOTES 🌸

πŸ’€ important vibe check: std::equal should not be used to compare the ranges formed by the iterators from std::unordered_set, std::unordered_multiset, std::unordered_map, or std::unordered_multimap because the order in which the elements are stored in those containers may be different even if the two containers store the same elements.

And when you're comparing entire containers for equality, operator== for the corresponding container is usually preferred 🫢 β€” that's the lowkey better move.


πŸŽ€ EXAMPLE πŸŽ€

this little demo uses std::equal to test if a string is a palindrome β€” palindrome checks are iconic, periodt ✨

// Run this code

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string_view>

constexpr bool is_palindrome(const std::string_view& s)
{
    return std::equal(s.cbegin(), s.cbegin() + s.size() / 2, s.crbegin());
}

void test(const std::string_view& s)
{
    std::cout << std::quoted(s)
              << (is_palindrome(s) ? " is" : " is not")
              << " a palindrome\n";
}

int main()
{
    test("radar");
    test("hello");
}

Output πŸ’¬

"radar" is a palindrome
"hello" is not a palindrome

πŸ¦‹ SEE ALSO πŸ¦‹

  • find, find_if, find_if_not (C++11) β€” finds the first element satisfying specific criteria; these are function templates 🫢
  • lexicographical_compare β€” returns true if one range is lexicographically less than another; function template 🌈
  • mismatch β€” finds the first position where two ranges differ; function template ✨
  • search β€” searches for a range of elements; function template πŸ”
  • ranges::equal (C++20) β€” determines if two sets of elements are the same; niebloid πŸ‘‘
  • equal_to β€” function object implementing x == y; class template πŸ’…
  • equal_range β€” returns range of elements matching a specific key; function template πŸŽ€

okay bye bestie πŸ’– this was std::equal(3) from http://cppreference.com, dated 2024.06.10 β€” mwah πŸ’‹

πŸ“¦ where this page comes from