Standard Template Library (STL)
The Standard Template Library (STL) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.
Components of the STL
1. Containers:
- Containers are objects that store collections of elements. They can be categorized into sequence containers and associative containers.
- Sequence Containers: vector, list, deque, array.
- Associative Containers: set, map, multiset, multimap.
2. Algorithms:
- Algorithms are a set of predefined functions that operate on containers and provide operations like sorting, searching, and modifying elements.
- Examples include
sort
,find
etc.
3. Iterators:
- Iterators are objects that allow the traversal of elements in a container.
- Categories include input iterators, output iterators, forward iterators, bidirectional iterators, and random access iterators.
4. Function Objects (Functors):
- Function objects are objects that behave like functions. They are often used with algorithms.
- Examples include
less
,greater
, and user-defined functors.
Sequence Containers
Vector
- Dynamic array with automatic resizing.
- Efficient random access (O(1)) and dynamic resizing.
- Suitable for scenarios where elements are frequently accessed and inserted at the end.
- Syntax:
vector <datatype> vectorname;
- Header File:
#include<vector>
- Modifiers:
push_back(val)
: Adds an element to the end.
pop_back()
: Removes the last element.
insert(iterator pos, val)
: Inserts an element at the specified position.
erase(iterator pos)
: Removes the element at the specified position.
- Capacity:
size()
: Returns the number of elements.
capacity()
: Returns the size of the allocated storage capacity.
resize(size_type n)
: Resizes the container to containn
elements.
reserve(size_type n)
: Requests that the vector capacity be at leastn
.
- Accessors:
front()
: Returns a reference to the first element.
back()
: Returns a reference to the last element.
data()
: Returns a pointer to the underlying array.
List
- Doubly-linked list.
- Efficient insertion and deletion anywhere in the list (O(1)).
- Suitable for scenarios where frequent insertions and deletions at various positions are required.
- Syntax:
list <datatype> listname;
- Header File:
#include<list>
- Modifiers:
push_back(val)
: Adds an element to the end.
pop_back()
: Removes the last element.
push_front(val)
: Adds an element to the beginning.
pop_front()
: Removes the first element.
insert(iterator pos, val)
: Inserts an element at the specified position.
erase(iterator pos)
: Removes the element at the specified position.
- Operations:
splice(iterator pos, x)
: Transfers elements from another list at the specified position.
merge(x)
: Merges sorted lists into the current list.
remove(val)
: Removes all elements with the specified value.
reverse()
: Reverses the order of elements.
sort()
: Sorts the elements.
- Capacity:
size()
: Returns the number of elements.
empty()
: Checks whether the list is empty.
- Iterators:
begin()
,end()
: Returns iterators to the beginning and end.
rbegin()
,rend()
: Returns reverse iterators to the reverse beginning and end.
Associative Containers
Set
- Ensures uniqueness and maintains elements in ascending order.
- Efficient search, insertion, and deletion operations (O(log n)).
- Suitable for scenarios where fast search operations and maintaining order are important.
- Syntax:
set <datatype> setname;
- Header File:
#include<set>
- Modifiers:
insert(val)
: Inserts an element.
erase(iterator pos)
: Removes the element at the specified position.
erase(val)
: Removes the element with the specified value.
clear()
: Removes all elements from the set.
- Operations:
find(val)
: Finds the iterator to the element with the specified value.
count(val)
: Counts the number of elements with the specified value.
- Iterators:
begin()
,end()
: Returns iterators to the beginning and end.
Map
- Stores key-value pairs where keys are unique and ordered.
- Suitable for scenarios where key-based search operations and maintaining order by key are important.
- Syntax:
map <key_type, value_type> mapname;
- Header File:
#include<map>
- Modifiers:
insert(Key,val)
: Inserts a key-value pair.
erase(iterator pos)
: Removes the element at the specified position.
erase(key)
: Removes the element with the specified key.
clear()
: Removes all elements from the map.
- Operations:
find(key)
: Finds the iterator to the element with the specified key.
- Iterators:
begin()
,end()
: Returns iterators to the beginning and end.
Algorithms provided by the STL
The Standard Template Library (STL) in C++ provides a rich set of algorithms that operate on various containers. These algorithms offer generic implementations for common tasks, such as searching, sorting, and modifying elements.
- Non-modifying Sequence Operations:
count
: Count occurrences of elements.
find
: Find the first occurrence of an element.
search
: Search for a subsequence or the last occurrence of a subsequence.
- Modifying Sequence Operations:
copy
: Copy elements from one range to another.
replace
: Replace occurrences of a value.
- Sorting and Related Operations:
sort
: Sort elements in a range .
merge
: Merge sorted ranges.
reverse
: Reverse elements in a range.
- Binary Search Operations:
binary_search
: Check if an element exists in a sorted range.
lower_bound
,upper_bound
: Find the lower and upper bounds of a value in a sorted range.
- Min/Max Operations:
min
,max
: Find the minimum or maximum of two values.
min_element
,max_element
: Find the minimum or maximum element in a range.
Iterators and their role in STL
Iterators are a fundamental concept in the Standard Template Library (STL) in C++. They act as an abstraction that allows traversing the elements of a container without exposing the underlying implementation details. Iterators provide a uniform interface for accessing elements in different types of containers, making algorithms in the STL generic and versatile.
Roles of Iterators in STL:
- Traversal:
- Role: Iterators allow you to traverse the elements of a container sequentially.
- Use: You can iterate over the entire container or specify a range of elements.
- Access to Elements:
- Role: Iterators provide a means to access individual elements within a container.
- Use: You can dereference an iterator to obtain the value of the element it points to.
- Insertion and Deletion:
- Role: Iterators enable the insertion and deletion of elements at the position pointed to by the iterator.
- Use: You can use iterators with insert and erase operations to modify the container.
- Range-Based Algorithms:
- Role: Many algorithms in the Standard Template Library (STL) are designed to work with iterators, allowing you to perform various operations on container elements.
- Use: Algorithms like
find
,sort
, and others take iterators as arguments.
- Generic Programming:
- Role: Iterators facilitate generic programming by providing a consistent interface for different container types.
- Use: Algorithms that use iterators can be applied to a variety of containers without modification.
Advantages of Iterators:
- Traversal of Containers:
- Iterators provide a way to traverse the elements of a container, allowing algorithms to access each element in a sequential manner.
- Uniform Interface:
- Regardless of the container type (e.g., vector, list, set), iterators provide a consistent interface for accessing elements, making algorithms generic and reusable.
- Range Specification:
- Iterators define ranges, specifying the beginning and end of a sequence. This enables algorithms to operate on specific subsets of elements within a container.
- Adaptability:
- Algorithms in the STL can be applied to any container as long as the container provides the required iterator interface. This adaptability is a key feature of the STL.
Applications of the STL
1. Data Structures Implementation
2. Algorithm Development
3. Containers for Storage
4. String Manipulation
5. File I/O Operations
6. Mathematical Computations
7. Graphical User Interface (GUI) Programming
8. Game Development
9. Database Applications
10. Educational Purposes
11. Embedded Systems
12. Networking Applications
Comparison of Various Containers in STL
Container | Description | Use Cases | Advantages | Disadvantages |
Vector | Dynamic array with automatic resizing. | Frequent random access, dynamic resizing. | Efficient random access (O(1)), dynamic resizing. | Insertions/deletions in the middle are inefficient (O(n)). |
List | Doubly-linked list. | Frequent insertions/deletions at various positions. | Efficient insertions/deletions anywhere (O(1)). | Inefficient random access (O(n)). |
Set | Balanced binary search tree (usually Red-Black Tree). | Maintaining a sorted and unique set of elements. | Efficient search, insertion, and deletion (O(log n)). | More memory overhead compared to vectors and lists. |
Map | Balanced binary search tree (usually Red-Black Tree) storing key-value pairs. | Associating values with unique keys. | Efficient key-based search, insertion, and deletion (O(log n)). | More memory overhead compared to vectors and lists. |