Namespaces
Variants

std:: equal

From cppreference.net
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
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
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
헤더 파일에 정의됨 <algorithm>
template < class InputIt1, class InputIt2 >

bool equal ( InputIt1 first1, InputIt1 last1,

InputIt2 first2 ) ;
(1) (C++20부터 constexpr)
template < class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >

bool equal ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 first2 ) ;
(2) (C++17부터)
template < class InputIt1, class InputIt2, class BinaryPred >

bool equal ( InputIt1 first1, InputIt1 last1,

InputIt2 first2, BinaryPred p ) ;
(3) (C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class BinaryPred >
bool equal ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 first2, BinaryPred p ) ;
(4) (C++17부터)
template < class InputIt1, class InputIt2 >

bool equal ( InputIt1 first1, InputIt1 last1,

InputIt2 first2, InputIt2 last2 ) ;
(5) (C++14부터)
(C++20부터 constexpr)
template < class ExecutionPolicy, class ForwardIt1, class ForwardIt2 >

bool equal ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 first2, ForwardIt2 last2 ) ;
(6) (C++17부터)
template < class InputIt1, class InputIt2, class BinaryPred >

bool equal ( InputIt1 first1, InputIt1 last1,

InputIt2 first2, InputIt2 last2, BinaryPred p ) ;
(7) (C++14부터)
(C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class BinaryPred >
bool equal ( ExecutionPolicy && policy,
ForwardIt1 first1, ForwardIt1 last1,

ForwardIt2 first2, ForwardIt2 last2, BinaryPred p ) ;
(8) (C++17부터)

[ first1 , last1 ) 범위와 first2 로 시작하는 범위가 동일한지 확인합니다:

  • 오버로드 (1-4) 의 경우, 두 번째 범위는 std:: distance ( first1, last1 ) 개의 요소를 가집니다.
  • 오버로드 (5-8) 의 경우, 두 번째 범위는 [ first2 , last2 ) 입니다.
1,5) 요소들은 operator == 를 사용하여 비교됩니다.
3,7) 요소들은 주어진 이항 조건자 p 를 사용하여 비교됩니다.
2,4,6,8) (1,3,5,7) 와 동일하지만, policy 에 따라 실행됩니다.
다음 모든 조건이 만족될 때만 이 오버로드들이 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 인 경우.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 인 경우.

(C++20 이후)

목차

매개변수

first1, last1 - 비교할 첫 번째 원소들의 범위 를 정의하는 반복자 쌍
first2, last2 - 비교할 두 번째 원소들의 범위 를 정의하는 반복자 쌍
policy - 사용할 실행 정책
p - 원소들이 동등한 것으로 처리되어야 할 경우 ​ true 를 반환하는 이항 predicate.

predicate 함수의 시그니처는 다음과 동일해야 함:

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

시그니처에 const & 가 필요하지는 않지만, 함수는 전달된 객체를 수정해서는 안 되며, 값 범주 에 관계없이 Type1 Type2 타입의 모든 값을 수용할 수 있어야 함 (따라서 Type1 & 는 허용되지 않으며, Type1 Type1 에 대해 이동이 복사와 동등하지 않는 한 허용되지 않음 (C++11부터) ).
Type1 Type2 타입은 InputIt1 InputIt2 타입의 객체가 역참조된 후 Type1 Type2 로 암시적으로 변환될 수 있어야 함. ​

타입 요구사항
-
InputIt1, InputIt2 LegacyInputIterator 요구사항을 충족해야 함.
-
ForwardIt1, ForwardIt2 LegacyForwardIterator 요구사항을 충족해야 함.
-
BinaryPred BinaryPredicate 요구사항을 충족해야 함.

반환값

1-4) 두 범위의 각 대응 요소가 동일하면 true 를 반환합니다. 그렇지 않으면 false 를 반환합니다.
5-8) 만약 std:: distance ( first1, last1 ) std:: distance ( first2, last2 ) 가 같고, 두 범위의 각 대응하는 요소들이 동일하다면 true 를 반환합니다. 그렇지 않으면 false 를 반환합니다.

복잡도

N 1 std:: distance ( first1, last1 ) 로, N 2 std:: distance ( first2, last2 ) 로 정의할 때:

1) 최대 N 1 번의 비교를 operator == 를 사용하여 수행합니다.
2) O(N 1 ) 번의 비교를 operator == 를 사용하여 수행합니다.
3) 최대 N 1 번의 술어 p 적용.
4) O(N 1 ) 술어 p 의 적용.
5-8) 만약 InputIt1 InputIt2 가 모두 LegacyRandomAccessIterator 이고, last1 - first1 ! = last2 - first2 true 인 경우, 어떠한 비교도 수행되지 않습니다.
그렇지 않으면, N min(N 1 ,N 2 ) 로 설정합니다:
5) 최대 N 번의 비교를 operator == 를 사용하여 수행합니다.
6) O(N) 번의 비교를 operator == 를 사용하여 수행합니다.
7) 최대 N 번의 술어 p 적용.
8) O(N) 술어 p 의 적용 횟수

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패하는 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

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 //< 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
{
    // 임의 접근 반복자 구현 (범위 크기 빠른 감지 가능)
    template<class RandomIt1, class RandomIt2>
    constexpr //< 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;
    }
    // 입력 반복자 구현 ("last2"와 수동 비교 필요)
    template<class InputIt1, class InputIt2>
    constexpr //< 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 //< 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
{
    // 임의 접근 반복자 구현 (범위 크기 빠른 감지 가능)
    template<class RandomIt1, class RandomIt2, class BinaryPred>
    constexpr //< 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;
    }
    // 입력 반복자 구현 ("last2"와 수동 비교 필요)
    template<class InputIt1, class InputIt2, class BinaryPred>
    constexpr //< 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 //< 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());
}

참고 사항

std::equal std::unordered_set , std::unordered_multiset , std::unordered_map , 또는 std::unordered_multimap 의 반복자들로 형성된 범위들을 비교하는 데 사용되어서는 안 됩니다. 왜냐하면 두 컨테이너가 동일한 요소들을 저장하더라도 이러한 컨테이너들에 요소들이 저장되는 순서가 다를 수 있기 때문입니다.

전체 컨테이너를 비교할 때 또는 string view (since C++17) 의 동등성을 확인할 때, operator == 가 해당 타입에 대해 일반적으로 선호됩니다.

순차적인 std::equal 는 단락 평가가 보장되지 않습니다. 예를 들어, 두 범위의 첫 번째 요소 쌍이 서로 같지 않을 경우 나머지 요소들도 비교될 수 있습니다. 단락 평가가 발생하지 않는 비교는 범위가 std::memcmp 또는 구현에 따른 벡터화된 알고리즘으로 비교될 때 발생할 수 있습니다.

예제

다음 코드는 std::equal 을 사용하여 문자열이 회문인지 테스트합니다.

#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");
}

출력:

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

참고 항목

특정 기준을 만족하는 첫 번째 요소를 찾음
(함수 템플릿)
한 범위가 다른 범위보다 사전순으로 작으면 true 반환
(함수 템플릿)
두 범위가 처음으로 달라지는 위치를 찾음
(함수 템플릿)
요소 범위의 첫 번째 발생을 검색
(함수 템플릿)
두 요소 집합이 동일한지 확인
(알고리즘 함수 객체)
x == y 를 구현하는 함수 객체
(클래스 템플릿)
특정 키와 일치하는 요소 범위를 반환
(함수 템플릿)