std::sort
cppreference : std::sort
https://en.cppreference.com/w/cpp/algorithm/sort
벡터는 <algorithm> 헤더에 있는 std::sort 함수로 퀵소트 정렬할 수 있다.
우선도가 같은 원소들의 순서는 보장되지 않기 때문에,
순서를 유지하고 싶다면 stable_sort를 사용하도록 하자.
std::sort는 벡터전용이 아니며, 임의 접근이 가능한
std::vector, std::array, std::deque에서 사용 가능하다.
std::list는 별도로 std::list::srot 함수가 있으며,
애초에 std::set이랑 std::map은 정렬된 상태로 저장하기 때문에 정렬할 필요가 없다.
std::sort 사용하기
기본형으로는
첫번째 인자 : 시작 이터레이터. 일반적으로 vector.begin() 사용
두 번째 인자 : 끝 이터레이터. 일반적으로 vector.end() 사용
시작과 끝 범위가 있기 때문에, 일부만을 지정하면 부분 정렬이 가능하다.
정렬은 오름차순을 사용한다.
std::sort(Iterator first, Iterator last);
내림차순으로 바꾸고 싶거나 별도의 기준을 정하고 싶다면 Compare를 따로 지정할 수 있다.
std::sort(Iterator first, Iterator last, Compare comp);
오름차순으로 정렬
std::sort(vec.begin(), vec.end());
내림차순으로 정렬
std::greater<int>() 를 사용하자.
std::sort(vec.begin(), vec.end(), std::greater<int>());
Compare 함수를 지정하여 정렬
// 사용자 정의 비교 함수 (짝수 우선, 그다음 오름차순)
bool customCompare(int a, int b) {
if ((a % 2 == 0) && (b % 2 != 0)) return true; // a가 짝수이고 b가 홀수
if ((a % 2 != 0) && (b % 2 == 0)) return false; // a가 홀수이고 b가 짝수
return a < b; // 기본 오름차순
}
std::sort(vec.begin(), vec.end(), customCompare);
람다로 정렬
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b; // 내림차순
});
'🌍 C++ Study > C++ 기초' 카테고리의 다른 글
C++ vector의 부분 벡터 구하기 (0) | 2024.11.20 |
---|---|
C++ std::count string의 문자 갯수 세기 std::count_if (0) | 2024.11.19 |
C++ string 문자열 뒤집기 std::reverse (0) | 2024.11.16 |
C++ string 부분 문자열 구하기 string::substr (0) | 2024.11.16 |
C++ 벡터에 연속된 숫자 채우기 std::iota (0) | 2024.11.15 |