The Standard Template Library (STL) is a collection of pre-built template classes and algorithms in C++ that provide common programming data structures and functions. It consists of parameterized components that make it highly reusable across different data types.
Containers store objects and data in organized ways. They are categorized into four types:
Store elements in a linear sequence:
Vector: A dynamic array with automatic resizing
#include <vector>
std::vector<int> numbers;
numbers.push_back(10); // Add element at the end
numbers.push_back(20);
int value = numbers[1]; // Random access using index (value = 20)
Deque: Double-ended queue supporting efficient insertion/deletion at both ends
#include <deque>
std::deque<std::string> messages;
messages.push_front("First"); // Add at beginning
messages.push_back("Last"); // Add at end
List: Doubly-linked list for efficient insertion/deletion at any position
#include <list>
std::list<float> values;
values.push_back(3.14);
auto it = values.begin();
values.insert(it, 2.71); // Insert before iterator position
Forward_list: Singly-linked list with reduced memory overhead
#include <forward_list>
std::forward_list<char> chars;
chars.push_front('A'); // Only supports push at front
chars.insert_after(chars.begin(), 'B'); // Insert after position
Implement sorted data structures for quick searching:
Set: Collection of unique keys, sorted automatically
#include <set>
std::set<int> uniqueNumbers;
uniqueNumbers.insert(30);
uniqueNumbers.insert(10);
uniqueNumbers.insert(30); // Duplicate not inserted
// Container now contains: 10, 30 (sorted order)
Map: Collection of key-value pairs, sorted by unique keys
#include <map>
std::map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
int aliceScore = scores["Alice"]; // Access by key
Multiset: Like set but allows duplicate keys
#include <set>
std::multiset<int> numbers;
numbers.insert(10);
numbers.insert(10); // Duplicate allowed
numbers.insert(20);
// Container now contains: 10, 10, 20
Multimap: Like map but allows duplicate keys
#include <map>
std::multimap<std::string, int> employeeAges;
employeeAges.insert({"Department A", 32});
employeeAges.insert({"Department A", 45}); // Same key allowed
Hash-based versions of the associative containers:
unordered_set, unordered_multiset, unordered_map, unordered_multimap
#include <unordered_map>std::unordered_map<std::string, int> fastLookup;fastLookup["key1"] = 100;// Access is O(1) on average vs O(log n) for map