C++ Standard Template Library (STL) Tutorial
The Standard Template Library (STL) in C++ is a powerful collection of classes and functions for data structures and algorithms. It includes containers, iterators, and algorithms that simplify common programming tasks.
Containers
STL provides several container types:
- Sequence Containers:
vector,deque,list. - Associative Containers:
set,map,multiset,multimap. - Derived Containers:
stack,queue,priority_queue.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
for (int n : numbers) {
cout << n << " ";
}
return 0;
}
Iterators
Iterators are used to traverse through STL containers:
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3};
for (vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
return 0;
}
Algorithms
STL includes built-in algorithms for sorting, searching, and more:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> numbers = {5, 3, 1, 4, 2};
sort(numbers.begin(), numbers.end());
for (int n : numbers) {
cout << n << " ";
}
return 0;
}
Advantages of STL
- Reduces development time by providing pre-built data structures and algorithms.
- Increases code efficiency and safety.
- Improves portability across different platforms.
×