C++ and STL
[STL] 컨테이너 정렬상태 확인 is_sorted()
Platent
2022. 3. 6. 11:48
C++ STL의 <algorithm> 헤더에는 컨테이너의 정렬과 관련된 여러가지 함수가 포함되어 있다. 이 중에 is_sorted() 메서드를 이용하면 컨테이너의 정렬상태를 쉽게 확인할 수 있다. 아래의 예제는 숫자를 1부터 8까지 받아서 이 숫자들이 오름차순으로 정렬되어 있으면 "ascending"을 내림차순으로 정렬되어 있으면 "descending"을 정렬되어 있지 않으면 "mixed"를 반환한다.
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
array<int, 8> arr;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
for (int i = 0; i < arr.size(); i++)
cin >> arr[i];
if (is_sorted(arr.begin(), arr.end()))
cout << "ascending" << '\n';
else if (is_sorted(arr.begin(), arr.end(), greater<int>()))
cout << "descending" << '\n';
else
cout << "mixed" << '\n';
return 0;
}