이 섹션에서는 C++의 표준 라이브러리를 사용하여 일부 배열 또는 연결 목록을 정렬하는 방법을 볼 것입니다. C++에는 다양한 용도로 사용할 수 있는 여러 라이브러리가 있습니다. 정렬도 그 중 하나입니다.
C++ 함수 std::list::sort()는 목록의 요소를 오름차순으로 정렬합니다. 동일한 요소의 순서가 유지됩니다. 비교를 위해 operator<를 사용합니다.
예시
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l = {1, 4, 2, 5, 3};
cout << "Contents of list before sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
l.sort();
cout << "Contents of list after sort operation" << endl;
for (auto it = l.begin(); it != l.end(); ++it)
cout << *it << endl;
return 0;
} 출력
Contents of list before sort operation 1 4 2 5 3 Contents of list after sort operation 1 2 3 4 5