C++에서 std::list는 요소를 이중 연결 리스트로 저장하는 시퀀스 컨테이너입니다. 이 구조는 시퀀스 내 어느 위치에서든 상수 시간에 항목 삽입/삭제 가능하며, 양방향 순회 지원. std::vector 같은 빠른 랜덤 액세스는 제공하지 않으나, 빈번한 삽입/삭제 발생 시나리오에서 탁월합니다.
컨테이너가 할당자(allocator)로 메모리 자동 관리해 런타임 중 양끝에서 성장/축소 가능.
왜 std::list 사용?
시퀀스 내 어디든 상수 시간 삽입/삭제.
요소 빈번 이동 알고리즘에 효율적.
컨테이너 크기 예측 불가할 때 이상적.
리스트 정의
std::list 사용 위해 <list> 헤더 포함:
#include <list> // 템플릿 정의 // template<class T, class Alloc = std::allocator<T>> class list;
매개변수:
T – 저장 요소 타입. 복사 생성 가능 타입 허용.
Alloc – 할당자 타입. 기본 std::allocator 보통 충분.
예제 1: 기본 순회
#include <iostream> #include <list> int main() { std::list<int> my_list{12, 5, 10, 9}; for (int x : my_list) { std::cout << x << '\n'; } }
#include <iostream> #include <list> int main() { std::list<int> l; // 빈 리스트 std::list<int> l1{10, 20, 30}; std::list<int> l2(l1.begin(), l1.end()); // 범위 복사 std::list<int> l3(std::move(l1)); // 이동 std::cout << "Size of l: " << l.size() << '\n'; std::cout << "Contents of l2:\n"; for (int x : l2) std::cout << x << '\n'; std::cout << "Contents of l3:\n"; for (int x : l3) std::cout << x << '\n'; }
출력:
컨테이너 특성
시퀀스 – 위치로 접근 가능한 선형 순서로 요소 저장.
이중 연결 리스트 – 각 노드가 선행·후행 노드 알아 상수 시간 삽입/삭제 가능.
할당자 인식 – 필요 시 할당자로 메모리 요청.
요소 삽입
push_front, push_back, insert로 항목 추가.
예제 3: 혼합 삽입
#include <algorithm> #include <iostream> #include <list> int main() { std::list<int> my_list{12, 5, 10, 9}; my_list.push_front(11); // 앞 my_list.push_back(18); // 뒤 auto it = std::find(my_list.begin(), my_list.end(), 10); if (it != my_list.end()) { my_list.insert(it, 21); // 10 앞 } for (int x : my_list) std::cout << x << '\n'; }
출력:
요소 삭제
erase로 단일 요소나 범위 제거.
예제 4: 삭제 시연
#include <iostream> #include <list> int main() { std::list<int> my_list{12, 5, 10, 9}; std::cout << "Before deletion:\n"; for (int x : my_list) std::cout << x << '\n'; my_list.erase(my_list.begin()); // 첫 요소 제거 std::cout << "After deletion:\n"; for (int x : my_list) std::cout << x << '\n'; }