Namespaces
Variants

std::basic_string<CharT,Traits,Allocator>:: compare

From cppreference.net
std::basic_string
int compare ( const basic_string & str ) const ;
(1) (C++11부터 noexcept)
(C++20부터 constexpr)
int compare ( size_type pos1, size_type count1,
const basic_string & str ) const ;
(2) (C++20부터 constexpr)
(3)
int compare ( size_type pos1, size_type count1,

const basic_string & str,

size_type pos2, size_type count2 ) const ;
(C++14까지)
int compare ( size_type pos1, size_type count1,

const basic_string & str,

size_type pos2, size_type count2 = npos ) const ;
(C++14부터)
(C++20부터 constexpr)
int compare ( const CharT * s ) const ;
(4) (C++20부터 constexpr)
int compare ( size_type pos1, size_type count1,
const CharT * s ) const ;
(5) (C++20부터 constexpr)
int compare ( size_type pos1, size_type count1,
const CharT * s, size_type count2 ) const ;
(6) (C++20부터 constexpr)
template < class StringViewLike >
int compare ( const StringViewLike & t ) const noexcept ( /* see below */ ) ;
(7) (C++17부터)
(C++20부터 constexpr)
template < class StringViewLike >

int compare ( size_type pos1, size_type count1,

const StringViewLike & t ) const ;
(8) (C++17부터)
(C++20부터 constexpr)
template < class StringViewLike >

int compare ( size_type pos1, size_type count1,
const StringViewLike & t,

size_type pos2, size_type count2 = npos ) const ;
(9) (C++17부터)
(C++20부터 constexpr)

두 문자 시퀀스를 비교합니다.

1) 이 문자열을 str 과 비교합니다.
2) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 str 와 비교합니다.
  • 만약 count1 > size ( ) - pos1 인 경우, 부분 문자열은 [ pos1 , size ( ) ) 입니다.
3) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 [ pos2 , pos2 + count2 ) 부분 문자열과 비교합니다.
  • 만약 count1 > size ( ) - pos1 이면, 첫 번째 부분 문자열은 [ pos1 , size ( ) ) 입니다.
  • 만약 count2 > str. size ( ) - pos2 이면, 두 번째 부분 문자열은 [ pos2 , str. size ( ) ) 입니다.
4) 이 문자열을 s 가 가리키는 문자에서 시작하는 널 종료 문자 시퀀스와 Traits :: length ( s ) 길이로 비교합니다.
5) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 s 가 가리키는 문자에서 시작하는 null-terminated 문자 시퀀스와 Traits :: length ( s ) 길이로 비교합니다.
  • 만약 count1 > size ( ) - pos1 이면, 부분 문자열은 [ pos1 , size ( ) ) 입니다.
6) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 [ s , s + count2 ) 범위의 문자들과 비교합니다. [ s , s + count2 ) 범위의 문자들은 null 문자를 포함할 수 있습니다.
  • 만약 count1 > size ( ) - pos1 인 경우, 부분 문자열은 [ pos1 , size ( ) ) 가 됩니다.
7-9) t 를 마치 std:: basic_string_view < CharT, Traits > sv = t ; 와 같이 문자열 뷰 sv 로 암시적으로 변환한 다음,
7) 이 문자열을 sv 와 비교합니다;
8) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 sv 와 비교합니다. 마치 std:: basic_string_view < CharT, Traits > ( * this ) . substr ( pos1, count1 ) . compare ( sv ) 를 사용한 것처럼;
9) 이 문자열의 [ pos1 , pos1 + count1 ) 부분 문자열을 [ pos2 , pos2 + count2 ) 부분 문자열과 비교합니다. sv 의, 마치 std:: basic_string_view < CharT, Traits > ( * this )
. substr ( pos1, count1 ) . compare ( sv. substr ( pos2, count2 ) )
와 같이.
이 오버로드들은 다음 조건이 충족될 때만 오버로드 해결에 참여합니다: std:: is_convertible_v < const StringViewLike & ,
std:: basic_string_view < CharT, Traits >>
true 이고 std:: is_convertible_v < const StringViewLike & , const CharT * > false 인 경우입니다.

count1 개의 문자로 이루어진 문자 시퀀스가 data1 에서 시작하고, count2 개의 문자로 이루어진 문자 시퀀스가 data2 에서 시작하는 두 시퀀스를 다음과 같이 비교합니다:

  • 먼저, 비교할 문자 수를 다음과 같이 계산합니다. size_type rlen = std:: min ( count1, count2 ) .
  • 그런 다음 다음을 호출하여 시퀀스를 비교합니다. Traits :: compare ( data1, data2, rlen ) . 표준 문자열의 경우 이 함수는 문자 단위의 사전식 비교를 수행합니다. 결과가 0이면(지금까지 문자 시퀀스가 동일함) 크기를 다음과 같이 비교합니다:
조건 결과 반환 값
Traits::compare( data1 , data2 , rlen ) < 0 data1 data2 보다 작음 < 0
Traits::compare( data1 , data2 , rlen ) == 0 size1 < size2 data1 data2 보다 작음 < 0
size1 == size2 data1 data2 와 같음 0
size1 > size2 data1 data2 보다 큼 > 0
Traits::compare( data1 , data2 , rlen ) > 0 data1 data2 보다 큼 > 0

목차

매개변수

str - 비교할 다른 문자열
s - 비교할 문자 문자열에 대한 포인터
count1 - 비교할 이 문자열의 문자 수
pos1 - 비교할 이 문자열의 첫 번째 문자 위치
count2 - 비교할 주어진 문자열의 문자 수
pos2 - 비교할 주어진 문자열의 첫 번째 문자 위치
t - 비교할 객체 ( std::basic_string_view 로 변환 가능)

반환값

  • 인수로 지정된 문자 시퀀스보다 사전식 순서에서 * this 가 앞서는 경우 음수 값
  • 두 문자 시퀀스가 동등하게 비교되는 경우 0
  • 인수로 지정된 문자 시퀀스보다 사전식 순서에서 * this 가 뒤따르는 경우 양수 값

예외

pos1 또는 pos2 매개변수를 취하는 오버로드는 인수가 범위를 벗어날 경우 std::out_of_range 를 발생시킵니다.

7)
noexcept 명세:
noexcept ( std:: is_nothrow_convertible_v < const T & , std:: basic_string_view < CharT, Traits >> )
8,9) 변환이 std::basic_string_view 로 수행될 때 발생하는 모든 예외를 전파합니다.

어떤 이유로든 예외가 발생하면, 이 함수는 아무런 효과를 가지지 않습니다( strong exception safety guarantee ).

가능한 구현

오버로드 (1)
template<class CharT, class Traits, class Alloc>
int std::basic_string<CharT, Traits, Alloc>::compare
    (const std::basic_string& s) const noexcept
{
    size_type lhs_sz = size();
    size_type rhs_sz = s.size();
    int result = traits_type::compare(data(), s.data(), std::min(lhs_sz, rhs_sz));
    if (result != 0)
        return result;
    if (lhs_sz < rhs_sz)
        return -1;
    if (lhs_sz > rhs_sz)
        return 1;
    return 0;
}

참고 사항

3방향 비교가 필요하지 않은 상황의 경우, std::basic_string 은 일반적인 관계 연산자들 ( < , <= , == , > , 등)을 제공합니다.

기본적으로 (기본 std::char_traits 사용 시), 이 함수는 로캘에 민감하지 않습니다. 로캘을 인식하는 3-way 문자열 비교를 위해서는 std::collate::compare 을 참조하십시오.

예제

#include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <string_view>
void print_compare_result(std::string_view str1,
                          std::string_view str2,
                          int compare_result)
{
    if (compare_result < 0)
        std::cout << std::quoted(str1) << " comes before "
                  << std::quoted(str2) << ".\n";
    else if (compare_result > 0)
        std::cout << std::quoted(str2) << " comes before "
                  << std::quoted(str1) << ".\n";
    else
        std::cout << std::quoted(str1) << " and "
                  << std::quoted(str2) << " are the same.\n";
}
int main()
{
    std::string batman{"Batman"};
    std::string superman{"Superman"};
    int compare_result{0};
    // 1) 다른 문자열과 비교
    compare_result = batman.compare(superman);
    std::cout << "1) ";
    print_compare_result("Batman", "Superman", compare_result);
    // 2) 부분 문자열을 다른 문자열과 비교
    compare_result = batman.compare(3, 3, superman);
    std::cout << "2) ";
    print_compare_result("man", "Superman", compare_result);
    // 3) 부분 문자열을 다른 부분 문자열과 비교
    compare_result = batman.compare(3, 3, superman, 5, 3);
    std::cout << "3) ";
    print_compare_result("man", "man", compare_result);
    // 부분 문자열을 다른 부분 문자열과 비교
    // 기본적으로 다른 문자열의 끝까지
    assert(compare_result == batman.compare(3, 3, superman, 5));
    // 4) char 포인터와 비교
    compare_result = batman.compare("Superman");
    std::cout << "4) ";
    print_compare_result("Batman", "Superman", compare_result);
    // 5) 부분 문자열을 char 포인터와 비교
    compare_result = batman.compare(3, 3, "Superman");
    std::cout << "5) ";
    print_compare_result("man", "Superman", compare_result);
    // 6) 부분 문자열을 char 포인터 부분 문자열과 비교
    compare_result = batman.compare(0, 3, "Superman", 5);
    std::cout << "6) ";
    print_compare_result("Bat", "Super", compare_result);
}

출력:

1) "Batman" comes before "Superman".
2) "Superman" comes before "man".
3) "man" and "man" are the same.
4) "Batman" comes before "Superman".
5) "Superman" comes before "man".
6) "Bat" comes before "Super".

결함 보고서

다음 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 수정된 동작
LWG 5 C++98 오버로드 (6) 의 매개변수 count2
기본 인수 npos 가 있었음
기본 인수 제거됨,
오버로드 (5) (6) 로 분할됨
LWG 847 C++98 예외 안전성 보장이 없었음 강력한 예외 안전성 보장 추가됨
LWG 2946 C++17 오버로드 (7) 가 일부 경우에
모호성을 야기함
템플릿으로 만들어 회피함
P1148R0 C++17 오버로드 (7) 의 noexcept가
LWG2946 해결로 인해
실수로 제거됨
복원됨

참고 항목

(C++20에서 제거됨) (C++20에서 제거됨) (C++20에서 제거됨) (C++20에서 제거됨) (C++20에서 제거됨) (C++20)
두 문자열을 사전식으로 비교함
(함수 템플릿)
부분 문자열을 반환함
(public 멤버 함수)
문자열의 사전식 비교와 해싱을 정의함
(클래스 템플릿)
현재 로캘에 따라 두 문자열을 비교함
(함수)
한 범위가 다른 범위보다 사전식으로 작으면 true 를 반환함
(함수 템플릿)
두 뷰를 비교함
( std::basic_string_view<CharT,Traits> 의 public 멤버 함수)