algorithm_equal
algorithm_equal (두 범위 동등 비교)
std::equal은 두 대상 범위가 서로 같은 요소를 담고 있는지 검사해요. 각 대응 위치의 요소를 차례로 비교해요.
출처: cppreference
본문
std::equal은 두 대상 범위 [first1, last1)과 [first2, last2)가 같은지 검사해요. last2 매개변수가 없는 오버로드에서는 last2를 std::next(first2, std::distance(first1, last1))로 간주해요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
InputIt2 first2 );
template< class InputIt1, class InputIt2, class BinaryPred >
bool equal( InputIt1 first1, InputIt1 last1,
InputIt2 first2, BinaryPred p );
template< class InputIt1, class InputIt2 >
bool equal( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2 );
template< class InputIt1, class InputIt2, class BinaryPred >
bool equal( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2, BinaryPred p );
operator==오버로드 — 요소를operator==로 비교해요.p오버로드 — 요소를 이진 술어p로 비교해요.- 병렬 실행 정책을 받는 오버로드도 있어요.
반환값 (Return value)
두 대상 범위의 크기가 같고 모든 대응 요소가 같으면 true, 아니면 false예요.
복잡도 (Complexity)
N₁을 std::distance(first1, last1), N₂를 std::distance(first2, last2)라고 하면 min(N₁, N₂)번 이하의 비교(또는 p 적용)가 필요해요. 두 범위 모두 RandomAccessIterator를 만족하고 N₁ ≠ N₂이면 비교를 전혀 하지 않아요.
참고 (Notes)
std::equal은 순서가 무의미한 std::unordered_set 계열 컨테이너의 범위를 비교하는 데 쓰면 안 돼요. 전체 컨테이너나 문자열 뷰의 동등성을 비교할 땐 해당 타입의 operator==가 보통 더 좋아요.
std::equal은 순차 실행 시 단락(short-circuit)을 보장하지 않아요. 예를 들어 첫 요소 쌍이 같지 않아도 나머지 요소가 계속 비교될 수 있어요.
예제 (Example)
#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