Namespaces
Variants

std::equal

cppreference.net에서
 
 
알고리즘 라이브러리
제한된 알고리즘 및 범위 알고리즘 (C++20)
제한된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 검색 연산
(분할된 범위에 대해)
집합 연산 (정렬된 범위에 대해)
병합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
헤더 <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 에 따라 실행됩니다.
이 오버로드들은 다음 표현식의 값이 true 인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)

매개변수

first1, last1 - 비교할 첫 번째 범위의 요소를 정의하는 반복자 쌍
first2, last2 - 비교할 두 번째 범위의 요소를 정의하는 반복자 쌍
policy - 사용할 실행 정책
p - 요소를 같음으로 처리해야 하면 ​true 를 반환하는 이진 술어.

술어 함수의 서명은 다음과 동등해야 합니다:

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

서명에 const & 가 있을 필요는 없지만, 함수는 전달된 객체를 수정해서는 안 되며 모든 (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 를 반환합니다.

복잡도

N1 을 std::distance(first1, last1) 로, N2 을 std::distance(first2, last2) 로 지정할 때:

1) 많아야 N1 번의 operator== 비교.
2) O(N1) 번의 operator== 비교.
3) 많아야 N1 번의 술어 p 적용.
4) O(N1) 번의 술어 p 적용.
5-8) InputIt1 와 InputIt2 가 모두 LegacyRandomAccessIterator 이고 last1 - first1 != last2 - first2 가 true 인 경우 비교가 수행되지 않습니다.
그렇지 않으면 N 을 min(N1,N2) 로 지정할 때:
5) 많아야 N 번의 operator== 비교.
6) O(N) 번의 operator== 비교.
7) 많아야 N 번의 술어 p 적용.
8) O(N) 번의 술어 p 적용.

예외

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

  • 알고리즘의 일부로 호출된 함수가 예외를 던지고 ExecutionPolicy 가 표준 정책 중 하나이면 std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현 정의입니다.
  • 알고리즘이 메모리 할당에 실패하면 std::bad_alloc 이 던져집니다.

가능한 구현

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());
}

참고

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

전체 컨테이너 또는 문자열 뷰(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

같이 보기

특정 기준을 충족하는 첫 번째 요소를 찾습니다
(함수 템플릿 & 알고리즘 함수 객체)
두 범위를 사전식으로 비교합니다
(함수 템플릿 & 알고리즘 함수 객체)
두 범위가 다른 첫 번째 위치를 찾습니다
(함수 템플릿 & 알고리즘 함수 객체)
요소 범위의 첫 번째 출현을 검색합니다
(함수 템플릿 & 알고리즘 함수 객체)
두 요소 집합이 동일한지 판단합니다
(알고리즘 함수 객체)
x == y
를 구현하는 함수 객체 (클래스 템플릿)
이진 검색을 사용하여 주어진 값과 일치하는 요소의 범위를 찾습니다
(함수 템플릿 & 알고리즘 함수 객체)