The Standard Template Library (STL) in C++ provides a set of template-based
classes and functions to efficiently handle common programming tasks like
managing collections of data, performing algorithms, and supporting iterators.
1. Components of STL
The STL is divided into four main components:
1. Containers: Classes to store and organize data.
2. Algorithms: Functions to perform operations like searching, sorting, etc.
3. Iterators: Objects that point to elements in a container.
4. Functors: Function objects that act like functions but are objects.
2. Containers
Containers are data structures that store data in various formats.
2.1 Types of Containers
1. Sequence Containers: Store elements in a linear sequence.
o Examples: vector, deque, list, array
2. Associative Containers: Store elements in a key-value pair.
o Examples: set, map, multiset, multimap
3. Unordered Containers: Similar to associative containers but use hashing for
faster access.
o Examples: unordered_set, unordered_map, unordered_multiset,
unordered_multimap
4. Container Adapters: Provide specific functionality using existing containers.
o Examples: stack, queue, priority_queue
2.2 Commonly Used Containers
, 1. Vector
o Dynamic array with random access.
o Example:
#include <vector>
std::vector<int> v = {1, 2, 3};
v.push_back(4); // Adds an element
v.pop_back(); // Removes last element
2. Map
o Stores key-value pairs in sorted order.
o Example:
#include <map>
std::map<int, std::string> m;
m[1] = "One";
m[2] = "Two";
3. Set
o Stores unique elements in sorted order.
o Example:
#include <set>
std::set<int> s = {3, 1, 2};
3. Algorithms
STL provides numerous algorithms to operate on containers. Algorithms work
with iterators.
3.1 Common Algorithms
1. Sort
o Sorts a range in ascending order.
Example: