The Standard Template Library (STL) is a collection of generic classes and functions that provides a set of common data structures and algorithms in C++. It is a part of the C++ Standard Library and is available in all modern C++ compilers.
The STL provides a set of containers, iterators, and algorithms that work together to provide a powerful and flexible toolset for C++ programmers. Some of the common STL containers include:
Vector: a dynamic array that can resize itself automatically.
List: a doubly-linked list that allows constant time insertion and deletion anywhere in the list.
Map: an associative array that allows mapping between keys and values.
Set: an ordered set of unique elements.
Queue: a first-in, first-out (FIFO) data structure.
Stack: a last-in, first-out (LIFO) data structure.
Hereβs an example of using some of these containers in C++:
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
list<string> l = {"foo", "bar", "baz"};
map<int, string> m = {{1, "one"}, {2, "two"}, {3, "three"}};
set<double> s = {3.14, 2.71, 1.41};
queue<char> q;
stack<char> st;
for (auto x : v) {
cout << x << " ";
}
cout << endl;
for (auto x : l) {
cout << x << " ";
}
cout << endl;
for (auto x : m) {
cout << x.first << " => " << x.second << endl;
}
for (auto x : s) {
cout << x << " ";
}
cout << endl;
q.push('a');
q.push('b');
q.push('c');
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
st.push('x');
st.push('y');
st.push('z');
while (!st.empty()) {
cout << st.top() << " ";
st.pop();
}
cout << endl;
return 0;
}
In this example, we create a vector of integers, a list of strings, a map of integers to strings, and a set of doubles, and iterate over them using range-based for loops. We also create a queue of characters and a stack of characters, and use the push and pop methods to add and remove elements from them.
By using STL containers and algorithms, we can write powerful and efficient code that works with a wide variety of data structures and use cases. The STL is an essential part of modern C++ programming, and provides a rich toolset for solving complex problems.