Programming

[c++]리스트 sort 하는 방법 (tistory.com)

steloflute 2023. 8. 20. 23:14

[c++]리스트 sort 하는 방법 (tistory.com)

 

[c++]리스트 sort 하는 방법

C++ #include #include int main() { std::list lst; lst.push_back(5); lst.push_back(1); std::sort(lst.begin(), lst.end()); return 0; } 당연하다는 듯이 이런 코드를 작성한 적이 있는데 sort 부분에서 에러가 뜬다. 이유는 아래와

blossoming-man.tistory.com

 

C++

#include <algorithm>
#include <list>

int main() {
std::list<int> lst;
    lst.push_back(5);
    lst.push_back(1);
    
    std::sort(lst.begin(), lst.end());
    return 0;
}

 


당연하다는 듯이 이런 코드를 작성한 적이 있는데 sort 부분에서 에러가 뜬다.

이유는 아래와 같다.

template<class RandomIt>
void sort( RandomIt first, RandomIt last );

RandomIt must meet the requirements of ValueSwappable and LegacyRandomAccessIterator.

 

std::sort 함수의 매개변수로 오는 반복자는 반드시 RandomAccessIterator 타입이어야 한다.

벡터는 반복자가 RandomAccessIterator 타입이므로 문제가 없었다.

 

그러나 리스트는 반복자가 BidirectionalIterator 타입이다. 그러니 <algorithm>에 정의되어 있는 std::sort를 리스트에 적용할 수 없다. 

대신 리스트에는 별도의 sort 함수가 제공되므로 코드를 아래와 같이 수정하면 사용 가능하다.

#include <list>

int main() {
std::list<int> lst;
    lst.push_back(5);
    lst.push_back(1);
    
    lst.sort();
    return 0;
}