algorithm_lexicographical_compare
algorithm_lexicographical_compare (사전식 비교)
std::lexicographical_compare는 두 대상 범위를 사전식(lexicographic)으로 비교해서 첫 번째 범위가 두 번째 범위보다 작은지 검사해요. 문자열 정렬과 같은 비교 규칙을 써요.
출처: cppreference
본문
std::lexicographical_compare는 첫 번째 대상 범위 [first1, last1)이 두 번째 대상 범위 [first2, last2)보다 사전식으로 작은지 검사해요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt1, class InputIt2 >
bool lexicographical_compare( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2 );
template< class InputIt1, class InputIt2, class Compare >
bool lexicographical_compare( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
Compare comp );
- 1번 오버로드 — 요소를
operator<로 비교해요. - 2번 오버로드 — 요소를 이진 비교 함수
comp로 비교해요. - 병렬 실행 정책을 받는 오버로드도 있어요.
사전식 비교는: 첫 번째 서로 다른 요소 쌍을 찾아서 두 요소를 비교하고, 그 결과를 돌려줘요. 일치하는 요소가 없으면(한 범위가 다른 범위의 접두어이면) 더 짧은 범위가 사전식으로 더 작아요.
반환값 (Return value)
첫 번째 범위가 사전식으로 두 번째 범위보다 작으면 true, 아니면 false예요.
복잡도 (Complexity)
최대 2·min(N₁, N₂)번의 비교가 필요해요 (여기서 N₁, N₂는 각 범위의 길이예요).
예제 (Example)
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> words{"apple", "banana", "cherry"};
std::cout << std::boolalpha
<< std::lexicographical_compare(words[0].begin(), words[0].end(),
words[1].begin(), words[1].end())
<< '\n';
}
출력:
true