이 글에서는 C++ STL의 list::clear() 함수의 동작 방식, 문법 그리고 실제 사용 예제에 대해 자세히 알아보겠습니다.
STL에서 리스트(List)란?
리스트는 시퀀스 내 어느 위치에서든 상수 시간(constant time)에 삽입과 삭제가 가능한 자료구조입니다. 리스트는 이중 연결 리스트(doubly linked list)로 구현되어 있으며, 비연속적인 메모리 할당을 허용합니다. 배열(array), 벡터(vector), 덱(deque)과 비교했을 때, 리스트는 컨테이너 내 임의의 위치에서 요소를 삽입, 추출, 이동하는 작업에서 더 나은 성능을 보입니다.
다만 리스트는 특정 요소에 직접 접근하는 속도가 느린 편이라는 점에 유의해야 합니다. 리스트는 forward_list와 유사하지만, forward_list 객체는 단일 연결 리스트(singly linked list)이며 앞쪽 방향으로만 순회할 수 있다는 차이점이 있습니다.
clear() 함수란?
list::clear()는 C++ STL에 내장된 함수로, <list> 헤더 파일에 선언되어 있습니다. list::clear()는 리스트 전체를 비우는 역할을 합니다. 즉, clear()는 리스트 컨테이너에 존재하는 모든 요소를 제거하고 컨테이너의 크기를 0으로 만듭니다.
문법
list_name.clear();
이 함수는 매개변수를 받지 않습니다.
반환 값
이 함수는 아무것도 반환하지 않으며, 단순히 컨테이너에서 모든 요소를 제거하는 역할만 수행합니다.
예제 1: 리스트 전체 비우기
아래 코드에서는 리스트에 요소들을 삽입한 후, clear() 함수를 적용하여 리스트 전체를 비워보겠습니다.
#include <iostream>
#include <list>
using namespace std;
int main(){
list<int> myList = { 10, 20, 30, 40, 50 };
cout<<"List before applying clear() function";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
//applying clear() function to clear the list
myList.clear();
for (auto i = myList.begin(); i!= myList.end(); ++i)
cout << ' ' << *i;
cout<<"\nlist is cleared ";
return 0;
}출력 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
List before applying clear() function 10 20 30 40 50 list is cleared
예제 2: 비운 후 새 요소 재삽입하기
아래 코드에서는 clear() 함수를 사용해 리스트 전체를 비운 후, 새로운 요소들을 다시 삽입하고 화면에 출력해 보겠습니다.
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> myList;
std::list<int>::iterator i;
myList.push_back (10);
myList.push_back (20);
myList.push_back (30);
cout<<"List before applying clear() function";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
myList.clear();
for (auto i = myList.begin(); i!= myList.end(); ++i)
cout << ' ' << *i;
cout<<"\nlist is cleared ";
myList.push_back (60);
myList.push_back (70);
cout<<"\nelements in my list are: ";
for (auto i=myList.begin(); i!=myList.end(); ++i)
cout<< ' ' << *i;
return 0;
}위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
List before applying clear() function 10 20 30 40 50 list is cleared Elements in my list are : 60 70