표준 템플릿 라이브러리 (STL)
1. 표준 템플릿 라이브러리 (STL) 소개
표준 템플릿 라이브러리(STL)는 C++의 강력한 기능 중 하나로, 다양한 데이터 구조와 알고리즘을 제공하여 프로그래밍을 더 효율적으로 만들어줍니다.
STL에는 여러 가지 유용한 컨테이너, 알고리즘, 반복자 등이 포함되어 있어 다양한 문제를 빠르고 간단하게 해결할 수 있습니다.
2. STL의 주요 컨테이너
2.1. vector
`vector`는 동적으로 크기가 조정되는 배열입니다. 배열처럼 인덱스를 통해 접근할 수 있으며, 크기가 자동으로 조정됩니다.
가장 자주 사용되는 컨테이너 중 하나입니다.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
for (int i : v) {
cout << i << " "; // 1 2 3 4 5
}
return 0;
}
2.2. list
`list`는 연결 리스트입니다. 데이터를 삽입하거나 삭제할 때 유용하지만, 인덱스로 접근하는 것이 비효율적입니다.
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> l = {10, 20, 30, 40, 50};
for (int i : l) {
cout << i << " "; // 10 20 30 40 50
}
return 0;
}
2.3. map
`map`은 키-값 쌍을 저장하는 연관 컨테이너입니다. 데이터를 키를 사용하여 빠르게 검색할 수 있습니다.
`map`은 기본적으로 데이터를 오름차순으로 정렬합니다.
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> m;
m["apple"] = 5;
m["banana"] = 2;
for (auto& pair : m) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
2.4. set
`set`은 중복 없는 데이터를 저장하는 컨테이너입니다. 자동으로 정렬되며, 특정 요소의 존재 여부를 빠르게 확인할 수 있습니다.
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s = {1, 2, 3, 4, 5};
for (int i : s) {
cout << i << " "; // 1 2 3 4 5
}
return 0;
}
3. 반복자 (Iterator)
반복자는 컨테이너의 요소에 접근할 수 있는 포인터와 같은 역할을 합니다. STL에서는 `begin()`과 `end()` 함수를 사용하여 반복자를 얻을 수 있습니다.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << " "; // 1 2 3 4 5
}
return 0;
}
4. 알고리즘 (Algorithm)
4.1. sort
`sort`는 컨테이너의 요소를 정렬하는 알고리즘입니다. 기본적으로 오름차순 정렬을 수행합니다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {5, 3, 8, 1, 4};
sort(v.begin(), v.end()); // 오름차순 정렬
for (int i : v) {
cout << i << " "; // 1 3 4 5 8
}
return 0;
}
4.2. find
`find`는 컨테이너에서 특정 요소를 찾는 알고리즘입니다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
auto it = find(v.begin(), v.end(), 30); // 30을 찾음
if (it != v.end()) {
cout << "Found: " << *it << endl; // Found: 30
}
return 0;
}
4.3. for_each
`for_each`는 컨테이너의 각 요소에 대해 주어진 함수나 람다를 적용하는 알고리즘입니다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
for_each(v.begin(), v.end(), [](int i) { cout << i << " "; });
return 0;
}
5. 함수 객체 (Functor)와 람다 함수
5.1. 함수 객체 (Functor)
함수 객체는 객체처럼 호출할 수 있는 객체입니다. 이를 통해 C++에서 함수처럼 동작하는 객체를 만들 수 있습니다.
#include <iostream>
#include <algorithm>
using namespace std;
class Print {
public:
void operator()(int n) const {
cout << n << " ";
}
};
int main() {
vector<int> v = {1, 2, 3, 4, 5};
for_each(v.begin(), v.end(), Print()); // 함수 객체 사용
return 0;
}
5.2. 람다 함수
람다 함수는 간단한 함수 정의를 위해 사용되는 익명 함수입니다. `[]`로 시작하여 함수 본체를 작성할 수 있습니다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
for_each(v.begin(), v.end(), [](int n) { cout << n << " "; }); // 람다 함수 사용
return 0;
}
마무리
STL은 C++에서 매우 강력한 도구입니다. 다양한 컨테이너, 알고리즘, 반복자, 함수 객체 및 람다 함수를 활용하여 더 효율적이고 간결한 코드를 작성할 수 있습니다.