[C++] STL 리스트(List)

Date:     Updated:

카테고리:

태그:

이 글은 C++ STL 리스트(List)를 공부하고 정리한 글입니다

리스트

  • 양방향 연결 리스트(이중 연결 리스트)
  • operator[]가 없음
  • 양쪽 끝에서 삽입/제거 가능

    코드 예시

    #include <list>
      
    int main()
    {
        std::list<int> scores;
        scores.push_front(10);    // 10
        scores.push_front(20);    // 20 10
        socres.push_back(30);     // 20 10 30
      
        return 0;
    }
    

    insert() / push_front() / push_back()

    // position이 가리키는 위치에 새 요소를 삽입한다
    iterator insert(iterator position, const value_type& val);
    
    // 제일 처음에 새 요소를 삽입한다
    void push_front(const value_type& value);
    
    // 제일 마지막에 새 요소를 삽입한다
    void push_back(const value_type& value);
    
    std::list<int> scores;
    std::list<int>::iterator it = scores.begin();
    
    scores.insert(it, 99);    // 99
    scores.push_front(10);    // 10 99
    scores.push_back(50);     // 10 99 50
    

    pop_front() / pop_back()

    // 처음 요소를 제거한다
    void pop_front();
    
    // 마지막 요소를 제거한다
    void pop_back();
    
    std::list<int> scores;    // 10 99 50
    
    scores.pop_front();       // 99 50
    scores.pop_back();        // 99
    

    erase() / remove()

    // position이 가리키는 위치의 요소를 제거한다
    iterator erase(iterator position);
    
    // value와 값이 같은 요소를 전부 제거한다
    void remove(const value_type& value);
    
    std::list<int> scores = { 20, 30, 40, 30, 25, 30, 70, 96 };
    std::list<int>::iterator it = scores.begin();
    
    scores.erase(it);     // 30 40 30 25 30 70 96
    scores.remove(30);    // 40 25 70 96
    

    장점

    • 삽입과 제거에 걸리는 시간: O(1)
    • 어느 위치든 삽입/제거 가능

    단점

    • 탐색이 느린 편
    • 임의적으로 접근 불가
    • 메모리가 불연속적


참조

포큐아카데미 C++ 언매니지드 프로그래밍



💻 열심히 공부해서 작성 중이니 오류나 틀린 부분이 있을 경우 
  언제든지 댓글 혹은 메일로 알려주시면 감사하겠습니다! 😸

맨 위로 이동하기

Cpp 카테고리 내 다른 글 보러가기

댓글 남기기