본문 바로가기
C++/기본

[C++] 21. STL

by 위니밍 2025. 3. 29.
반응형
📌 요약: STL | 연결 리스트 | 배열 | 벡터 | 스택 | 큐 | 힙 | 맵 | 집합

🔧 STL (Standard Template Library)

STL은 다양한 자료형에 대해 효율적인 알고리즘과 데이터 구조를 제공하는 라이브러리입니다. 주로 사용할 수 있는 연결 리스트, 배열, 스택, 큐, 맵, 집합과 같은 자료구조가 포함됩니다.

📌 연결 리스트 (Linked List)

연결 리스트는 각 노드가 자신의 다음 노드를 가리키는 방식으로 데이터를 저장하는 구조입니다. 주로 삽입과 삭제가 자주 발생할 때 유용합니다.

#include <iostream>
#include <list>

using namespace std;

int main() {
	// 리스트 선언
	list temp;

	// push_back -> 뒤에서 값 넣기
	for (int i = 0; i < 10; i++) {
		temp.push_back(i);
	}

	// push_front -> 앞에서 값 넣기
	for (int i = 0; i < 10; i++) {
		temp.push_front(i);
	}

	// insert(인덱스, 값)
	auto index = ++temp.begin();
	temp.insert(index, -1);

	// 출력
	for (int a : temp) {
		cout << a << " ";
	}
	cout << endl;

	// 맨앞 원소 제거하기
	temp.pop_front();

	// 맨뒤 원소 제거하기
	temp.pop_back();

	// 출력
	for (int a : temp) {
		cout << a << " ";
	}
	cout << endl;

	return 0;
}
📌 배열 (Array)

배열은 연속된 메모리 공간에 데이터를 저장하는 자료구조로, 인덱스를 이용해 데이터에 빠르게 접근할 수 있습니다. 연결 리스트와 달리 고정된 크기와 순차적인 접근을 제공합니다.

#include <iostream>

using namespace std;

int main() {
	const int count = 10;
	int temp[count];

	// 배열 초기화
	for (int i = 0; i < 10; i++) {
		temp[i] = i;
	}

	// 배열 출력
	for (int a : temp) {
		cout << a << " ";
	}
	cout << endl;

	// 인덱스를 통한 접근
	cout << temp[3] << endl;

	return 0;
}
📌 벡터 (Vector)

벡터는 크기가 동적으로 변하는 배열로, 순차적으로 데이터를 저장합니다. 추가, 삭제가 빈번한 경우 유용하며, 크기가 자동으로 조정됩니다.

#include <iostream>
#include <vector>

using namespace std;

int main() {
	// 순차리스트 생성
	vector container = vector(3);
	container[0] = "기본 데이터 0";
	container[1] = "기본 데이터 1";
	container[2] = "기본 데이터 2";

	// 추가
	container.push_back("추가 데이터 0");
	container.push_back("추가 데이터 1");
	container.push_back("추가 데이터 2");

	// 삭제
	container.pop_back(); // 추가 데이터 2 삭제

	// 순회
	for (int i = 0; i < container.size(); i++) {
		cout << container[i] << endl;
	}

	return 0;
}
📌 스택 (Stack)

스택은 LIFO (Last In, First Out) 구조로, 가장 나중에 들어온 요소가 먼저 나옵니다. 주로 함수 호출 시 스택을 활용하여 데이터를 저장합니다.

#include <iostream>
#include <stack>

using namespace std;

int main() {
	stack stk;

	// 요소 삽입
	for (int i = 0; i < 10; i++) {
		stk.push(i);
	}

	// 요소 제거
	int last = stk.top(); //9
	stk.pop();

	// 출력
	while (stk.size()) {
		cout << stk.top() << " ";
		stk.pop();
	}
	cout << endl;

	cout << last << endl; //9

	return 0;
}
📌 큐 (Queue)

큐는 FIFO (First In, First Out) 구조로, 가장 먼저 들어온 요소가 먼저 나옵니다. 주로 데이터 처리나 대기열 관리 등에 사용됩니다.

#include <iostream>
#include <queue>

using namespace std;

int main() {
	queue que;

	// 요소 추가
	for (int i = 0; i < 10; i++) {
		que.push(i);
	}

	// 요소 삭제
	int last = que.front();
	que.pop();

	// 출력
	while (que.size()) {
		cout << que.front() << " ";
		que.pop();
	}
	cout << endl;

	cout << "last : " << last << endl;

	return 0;
}
📌 우선순위 큐 (Priority Queue)

우선순위 큐는 각 요소에 우선순위를 부여하고, 우선순위가 높은 요소가 먼저 처리되는 자료구조입니다. 힙을 기반으로 구현됩니다.

#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
	priority_queue pq;

	int random_num[6] = {10, 30, 40, 50, 20};

	// 요소 삽입
	for (int i = 0; i < 6; i++) {
		pq.push(random_num[i]);
	}

	// 출력
	while (pq.size()) {
		cout << pq.top() << " ";
		pq.pop();
	}
	cout << endl;

	return 0;
}
📌 맵 (Map)

맵은 키와 값을 쌍으로 저장하는 연관 컨테이너입니다. 키는 유일하며, 값은 중복을 허용합니다. 맵은 기본적으로 자동으로 키를 정렬하여 저장합니다.

#include <iostream>
#include <map>

using namespace std;

int main() {
	map m;
	string keys[3] = {"David", "Paul", "Kevin"};

	// 요소 삽입
	m.insert({keys[0], 26});
	m.insert(make_pair(keys[1], 25));
	m[keys[2]] = 27;

	// 출력
	for (int i = 0; i < m.size(); i++) {
		cout << keys[i] << ":" << m[keys[i]] << " ";
	}
	cout << endl;

	// 요소 수정
	m[keys[2]] = 29;

	// 출력
	for (int i = 0; i < m.size(); i++) {
		cout << keys[i] << ":" << m[keys[i]] << " ";
	}
	cout << endl;

	// 요소 찾기
	if (m.find("Smith") != m.end()) {
		cout << "Find" << endl;
	} else {
		cout << "Not Found" << endl;
	}

	cout << endl;

	// Iterator 사용하여 출력
	map::iterator iter;
	for (iter = m.begin(); iter != m.end(); iter++) {
		cout << iter->first << ":" << iter->second << " ";
	}
	cout << endl;

	// 요소 삭제
	m.erase(++m.begin());
	for (auto i : m) {
		cout << i.first << ":" << i.second << " ";
	}
	cout << endl;

	// erase를 이용한 모든 요소 제거
	m.erase(m.begin(), m.end());
	for (auto i : m) {
		cout << "3. " << i.first << ":" << i.second << " ";
	}
	cout << endl;

	// clear 함수로 모든 요소 제거
	m.clear();
	for (auto i : m) {
		cout << i.first << ":" << i.second << " ";
	}
	cout << endl;

	return 0;
}
📌 집합 (Set)

집합은 중복을 허용하지 않으며, 요소들의 순서에 상관없이 값을 저장합니다. 주로 중복된 데이터를 처리하거나 유니크한 요소만 필요할 때 사용합니다.

#include <iostream>
#include <set>

using namespace std;

int main() {
	set s;
	int value[6] = {1, 4, 7, 10, 4, 4};

	// 요소 삽입
	for (int i : value) {
		s.insert(i);
	}

	// 출력
	set::iterator iter;
	for (iter = s.begin(); iter != s.end(); iter++) {
		cout << *iter << " ";
	}
	cout << endl;

	return 0;
}
🧪 실행 순서

1. 각 STL 자료구조를 생성하고 데이터를 삽입함.
2. 각 자료구조에 삽입/삭제/순회 등의 작업을 수행.
3. 벡터, 맵, 집합 등의 요소가 출력됨.
4. 메모리 해제 후 프로그램 종료.

반응형

'C++ > 기본' 카테고리의 다른 글

[C++] 23. Array  (0) 2025.03.29
[C++] 22. String 문자열  (0) 2025.03.29
[C++] 20. OOP - 추상  (0) 2025.03.29
[C++] 19. OOP - 다형성  (0) 2025.03.29
[C++] 18. OOP - 상속  (0) 2025.03.29