Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/algorithm/ranges/equal"

From cppreference.com
< cpp‎ | algorithm‎ | ranges
m (Example: ~ string -> string_view to avoid temproraries)
(Notes: + non-short-circuit comparison)
 
(10 intermediate revisions by 4 users not shown)
Line 2: Line 2:
 
{{cpp/algorithm/ranges/navbar}}
 
{{cpp/algorithm/ranges/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | algorithm}}
+
{{dcl header|algorithm}}
{{dcl h | Call signature}}
+
{{dcl h|Call signature}}
{{dcl | num=1 | since=c++20 |1=
+
{{dcl|num=1|since=c++20|1=
 
template< std::input_iterator I1, std::sentinel_for<I1> S1,
 
template< std::input_iterator I1, std::sentinel_for<I1> S1,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           class Pred = ranges::equal_to,
 
           class Pred = ranges::equal_to,
 
           class Proj1 = std::identity, class Proj2 = std::identity >
 
           class Proj1 = std::identity, class Proj2 = std::identity >
  requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
+
requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr bool equal( I1 first1, S1 last1, I2 first2, S2 last2,
+
constexpr bool
                      Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
+
    equal( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {},
 +
          Proj1 proj1 = {}, Proj2 proj2 = {} );
 
}}
 
}}
{{dcl | num=2 | since=c++20 |1=
+
{{dcl|num=2|since=c++20|1=
 
template< ranges::input_range R1, ranges::input_range R2,
 
template< ranges::input_range R1, ranges::input_range R2,
 
           class Pred = ranges::equal_to,
 
           class Pred = ranges::equal_to,
 
           class Proj1 = std::identity, class Proj2 = std::identity >
 
           class Proj1 = std::identity, class Proj2 = std::identity >
  requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
+
requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                                      Pred, Proj1, Proj2>
+
                                    Pred, Proj1, Proj2>
constexpr bool equal( R1&& r1, R2&& r2, Pred pred = {},
+
constexpr bool
                      Proj1 proj1 = {}, Proj2 proj2 = {} );
+
    equal( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
  
@1@ Returns {{c|true}} if the projected values of the range {{tt|[first1, last1)}} are equal to the projected values of the range {{tt|[first2, last2)}}, and {{c|false}} otherwise.
+
@1@ Returns {{c|true}} if the projected values of the range {{range|first1|last1}} are equal to the projected values of the range {{range|first2|last2}}, and {{c|false}} otherwise.
  
@2@ Same as {{v|1}}, but uses {{tt|r}} as the source range, as if using {{c|ranges::begin(r)}} as {{tt|first}} and {{c|ranges::end(r)}} as {{tt|last}}.
+
@2@ Same as {{v|1}}, but uses {{c|r}} as the source range, as if using {{c|ranges::begin(r)}} as {{c|first}} and {{c|ranges::end(r)}} as {{c|last}}.
  
Two ranges are considered equal if they have the same number of elements and every pair of corresponding projected elements satisfies {{tt|pred}}. That is, {{c|std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2))}} returns {{tt|true}} for all pairs of corresponding elements in both ranges.
+
Two ranges are considered equal if they have the same number of elements and every pair of corresponding projected elements satisfies {{c|pred}}. That is, {{c|std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2))}} returns {{c|true}} for all pairs of corresponding elements in both ranges.
  
 
{{cpp/ranges/niebloid}}
 
{{cpp/ranges/niebloid}}
Line 34: Line 35:
 
===Parameters===
 
===Parameters===
 
{{par begin}}
 
{{par begin}}
{{par | first1, last1 | an iterator-sentinel pair denoting the first range of the elements to compare}}
+
{{par|first1, last1|an iterator-sentinel pair denoting the first range of the elements to compare}}
{{par | r1 | the first range of the elements to compare}}
+
{{par|r1|the first range of the elements to compare}}
{{par | first2, last2 | an iterator-sentinel pair denoting the second range of the elements to compare}}
+
{{par|first2, last2|an iterator-sentinel pair denoting the second range of the elements to compare}}
{{par | r2 | the second range of the elements to compare}}
+
{{par|r2|the second range of the elements to compare}}
{{par | pred | predicate to apply to the projected elements}}
+
{{par|pred|predicate to apply to the projected elements}}
{{par | proj1 | projection to apply to the first range of elements}}
+
{{par|proj1|projection to apply to the first range of elements}}
{{par | proj2 | projection to apply to the second range of elements}}
+
{{par|proj2|projection to apply to the second range of elements}}
 
{{par end}}
 
{{par end}}
  
 
===Return value===
 
===Return value===
If the length of the range {{tt|[first1, last1)}} does not equal the length of the range {{tt|[first2, last2)}}, returns {{c|false}}.
+
If the length of the range {{range|first1|last1}} does not equal the length of the range {{range|first2|last2}}, returns {{c|false}}.
  
 
If the elements in the two ranges are equal after projection, returns {{c|true}}.
 
If the elements in the two ranges are equal after projection, returns {{c|true}}.
Line 53: Line 54:
 
{{tt|ranges::equal}} should not be used to compare the ranges formed by the iterators from {{lc|std::unordered_set}}, {{lc|std::unordered_multiset}}, {{lc|std::unordered_map}}, or {{lc|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.  
 
{{tt|ranges::equal}} should not be used to compare the ranges formed by the iterators from {{lc|std::unordered_set}}, {{lc|std::unordered_multiset}}, {{lc|std::unordered_map}}, or {{lc|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.  
  
When comparing entire containers for equality, {{tt|operator{{==}}}} for the corresponding container are usually preferred.
+
When comparing entire containers or string views for equality, {{c/core|1=operator==}} for the corresponding type are usually preferred.
 +
 
 +
{{tt|ranges::equal}} is not guaranteed to be short-circuit. E.g. if the first pair elements of both ranges do not compare equal, the rest of elements may also be compared. Non-short-circuit comparison may happen when the ranges are compared with {{lc|std::memcmp}} or implementation-specific vectorized algorithms.
  
 
===Complexity===
 
===Complexity===
At most min({{tt|last1}} - {{tt|first1}}, {{tt|last2}} - {{tt|first2}}) applications of the predicate and corresponding projections.
+
At most {{c|min(last1 - first1, last2 - first2)}} applications of the predicate and corresponding projections.
  
However, if {{tt|S1}} and {{tt|S2}} both model {{lc|std::sized_sentinel_for}} their respective iterators, and {{c|last1 - first1 !{{=}} last2 - first2}} then no applications of the predicate are made (size mismatch is detected without looking at any elements).
+
However, if {{c|S1}} and {{c|S2}} both model {{lc|std::sized_sentinel_for}} their respective iterators, and {{c|last1 - first1 !{{=}} last2 - first2}} then no applications of the predicate are made (size mismatch is detected without looking at any elements).
  
 
===Possible implementation===
 
===Possible implementation===
 
{{eq fun
 
{{eq fun
| 1=
+
|1=
struct equal_fn {
+
struct equal_fn
 +
{
 
   template<std::input_iterator I1, std::sentinel_for<I1> S1,
 
   template<std::input_iterator I1, std::sentinel_for<I1> S1,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           std::input_iterator I2, std::sentinel_for<I2> S2,
 
           class Pred = ranges::equal_to,
 
           class Pred = ranges::equal_to,
 
           class Proj1 = std::identity, class Proj2 = std::identity>
 
           class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
+
  requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
 
   constexpr bool
 
   constexpr bool
  operator()(I1 first1, S1 last1, I2 first2, S2 last2,
+
      operator()(I1 first1, S1 last1, I2 first2, S2 last2,
            Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
+
                Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
 
   {
 
   {
       if (ranges::distance(first1, last1) != ranges::distance(first2, last2)) {
+
       if constexpr (std::sized_sentinel_for<S1, I1> and std::sized_sentinel_for<S2, I2>)
        return false;
+
          if (std::ranges::distance(first1, last1) != std::ranges::distance(first2, last2))
      }
+
              return false;
  
       for (; first1 != last1; ++first1, (void)++first2) {
+
       for (; first1 != last1; ++first1, (void)++first2)
           if (!std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2))) {
+
           if (!std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2)))
 
               return false;
 
               return false;
          }
 
      }
 
 
       return true;
 
       return true;
 
   }
 
   }
  
   template<ranges::input_range R1, std::input_range R2,
+
   template<ranges::input_range R1, ranges::input_range R2,
 
           class Pred = ranges::equal_to,
 
           class Pred = ranges::equal_to,
 
           class Proj1 = std::identity, class Proj2 = std::identity>
 
           class Proj1 = std::identity, class Proj2 = std::identity>
    requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
+
  requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                                        Pred, Proj1, Proj2>
+
                                      Pred, Proj1, Proj2>
 
   constexpr bool
 
   constexpr bool
  operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
+
      operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
 
   {
 
   {
 
       return (*this)(ranges::begin(r1), ranges::end(r1),
 
       return (*this)(ranges::begin(r1), ranges::end(r1),
Line 104: Line 106:
 
===Example===
 
===Example===
 
{{example
 
{{example
| The following code uses {{c|equal()}} to test if a string is a palindrome.
+
|The following code uses {{lc|ranges::equal}} to test if a string is a palindrome.
| code=
+
|code=
 
#include <algorithm>
 
#include <algorithm>
 +
#include <iomanip>
 
#include <iostream>
 
#include <iostream>
#include <string_view>
 
 
#include <ranges>
 
#include <ranges>
 +
#include <string_view>
  
bool is_palindrome(const std::string_view s)
+
constexpr bool is_palindrome(const std::string_view s)
 
{
 
{
 
     namespace views = std::views;
 
     namespace views = std::views;
Line 121: Line 124:
 
void test(const std::string_view s)
 
void test(const std::string_view s)
 
{
 
{
     std::cout << "\"" << s << "\" is"
+
     std::cout << std::quoted(s) << " is "
        << (is_palindrome(s) ? "" : " not")
+
              << (is_palindrome(s) ? "" : "not ")
        << " a palindrome\n";
+
              << "a palindrome\n";
 
}
 
}
  
Line 130: Line 133:
 
     test("radar");
 
     test("radar");
 
     test("hello");
 
     test("hello");
 +
    static_assert(is_palindrome("ABBA") and not is_palindrome("AC/DC"));
 
}
 
}
| output=
+
|output=
 
"radar" is a palindrome
 
"radar" is a palindrome
 
"hello" is not a palindrome
 
"hello" is not a palindrome
Line 138: Line 142:
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/algorithm/ranges/dsc find}}
+
{{dsc inc|cpp/algorithm/ranges/dsc find}}
{{dsc inc | cpp/algorithm/ranges/dsc lexicographical_compare}}
+
{{dsc inc|cpp/algorithm/ranges/dsc lexicographical_compare}}
{{dsc inc | cpp/algorithm/ranges/dsc mismatch}}
+
{{dsc inc|cpp/algorithm/ranges/dsc mismatch}}
{{dsc inc | cpp/algorithm/ranges/dsc search}}
+
{{dsc inc|cpp/algorithm/ranges/dsc search}}
<!-- Does not work yet?
+
{{dsc inc|cpp/algorithm/ranges/dsc equal_range}}
{{dsc inc | cpp/algorithm/ranges/dsc take_view}}
+
{{dsc inc|cpp/utility/functional/dsc equal_to}}
{{dsc inc | cpp/algorithm/ranges/dsc reverse_view}}
+
{{dsc inc|cpp/algorithm/dsc equal}}
-->
+
{{dsc inc | cpp/algorithm/dsc equal}}
+
 
{{dsc end}}
 
{{dsc end}}
  
{{langlinks|es|ja|zh}}
+
{{langlinks|es|ja|ru|zh}}

Latest revision as of 18:46, 11 November 2024

 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
(C++11)                (C++11)(C++11)

Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17)(C++11)
(C++20)(C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
 
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
       
       
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
       
       
Permutation operations
Fold operations
Numeric operations
(C++23)            
Operations on uninitialized storage
Return types
 
Defined in header <algorithm>
Call signature
template< std::input_iterator I1, std::sentinel_for<I1> S1,

          std::input_iterator I2, std::sentinel_for<I2> S2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr bool
    equal( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {},

           Proj1 proj1 = {}, Proj2 proj2 = {} );
(1) (since C++20)
template< ranges::input_range R1, ranges::input_range R2,

          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                                    Pred, Proj1, Proj2>
constexpr bool

    equal( R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
(2) (since C++20)
1) Returns true if the projected values of the range [first1last1) are equal to the projected values of the range [first2last2), and false otherwise.
2) Same as (1), but uses r as the source range, as if using ranges::begin(r) as first and ranges::end(r) as last.

Two ranges are considered equal if they have the same number of elements and every pair of corresponding projected elements satisfies pred. That is, std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2)) returns true for all pairs of corresponding elements in both ranges.

The function-like entities described on this page are niebloids, that is:

In practice, they may be implemented as function objects, or with special compiler extensions.

Contents

[edit] Parameters

first1, last1 - an iterator-sentinel pair denoting the first range of the elements to compare
r1 - the first range of the elements to compare
first2, last2 - an iterator-sentinel pair denoting the second range of the elements to compare
r2 - the second range of the elements to compare
pred - predicate to apply to the projected elements
proj1 - projection to apply to the first range of elements
proj2 - projection to apply to the second range of elements

[edit] Return value

If the length of the range [first1last1) does not equal the length of the range [first2last2), returns false.

If the elements in the two ranges are equal after projection, returns true.

Otherwise returns false.

[edit] Notes

ranges::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.

When comparing entire containers or string views for equality, operator== for the corresponding type are usually preferred.

ranges::equal is not guaranteed to be short-circuit. E.g. if the first pair elements of both ranges do not compare equal, the rest of elements may also be compared. Non-short-circuit comparison may happen when the ranges are compared with std::memcmp or implementation-specific vectorized algorithms.

[edit] Complexity

At most min(last1 - first1, last2 - first2) applications of the predicate and corresponding projections.

However, if S1 and S2 both model std::sized_sentinel_for their respective iterators, and last1 - first1 != last2 - first2 then no applications of the predicate are made (size mismatch is detected without looking at any elements).

[edit] Possible implementation

struct equal_fn
{
  template<std::input_iterator I1, std::sentinel_for<I1> S1,
           std::input_iterator I2, std::sentinel_for<I2> S2,
           class Pred = ranges::equal_to,
           class Proj1 = std::identity, class Proj2 = std::identity>
  requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
  constexpr bool
      operator()(I1 first1, S1 last1, I2 first2, S2 last2,
                 Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
  {
      if constexpr (std::sized_sentinel_for<S1, I1> and std::sized_sentinel_for<S2, I2>)
          if (std::ranges::distance(first1, last1) != std::ranges::distance(first2, last2))
              return false;
 
      for (; first1 != last1; ++first1, (void)++first2)
          if (!std::invoke(pred, std::invoke(proj1, *first1), std::invoke(proj2, *first2)))
              return false;
      return true;
  }
 
  template<ranges::input_range R1, ranges::input_range R2,
           class Pred = ranges::equal_to,
           class Proj1 = std::identity, class Proj2 = std::identity>
  requires std::indirectly_comparable<ranges::iterator_t<R1>, ranges::iterator_t<R2>,
                                      Pred, Proj1, Proj2>
  constexpr bool
      operator()(R1&& r1, R2&& r2, Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
  {
      return (*this)(ranges::begin(r1), ranges::end(r1),
                     ranges::begin(r2), ranges::end(r2),
                     std::ref(pred), std::ref(proj1), std::ref(proj2));
  }
};
 
inline constexpr equal_fn equal;

[edit] Example

The following code uses ranges::equal to test if a string is a palindrome.

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <ranges>
#include <string_view>
 
constexpr bool is_palindrome(const std::string_view s)
{
    namespace views = std::views;
    auto forward = s | views::take(s.size() / 2);
    auto backward = s | views::reverse | views::take(s.size() / 2);
    return std::ranges::equal(forward, backward);
}
 
void test(const std::string_view s)
{
    std::cout << std::quoted(s) << " is "
              << (is_palindrome(s) ? "" : "not ")
              << "a palindrome\n";
}
 
int main()
{
    test("radar");
    test("hello");
    static_assert(is_palindrome("ABBA") and not is_palindrome("AC/DC"));
}

Output:

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

[edit] See also

finds the first element satisfying specific criteria
(niebloid)[edit]
returns true if one range is lexicographically less than another
(niebloid)[edit]
finds the first position where two ranges differ
(niebloid)[edit]
searches for the first occurrence of a range of elements
(niebloid)[edit]
returns range of elements matching a specific key
(niebloid)[edit]
function object implementing x == y
(class template) [edit]
determines if two sets of elements are the same
(function template) [edit]