The Standard Template Library (STL) - GitMasterNikanjam/C_WiKi GitHub Wiki
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. The STL was introduced to the C++ Standard in the late 1990s and is an integral part of the C++ Standard Library.
Sequence Containers:
std::vector: Dynamic array.
std::list: Doubly-linked list.
std::deque: Double-ended queue.
Associative Containers:
std::set: Ordered set.
std::map: Ordered key-value map.
std::multiset and std::multimap: Allow duplicate elements.
Container Adapters:
std::stack: LIFO stack.
std::queue: FIFO queue.
std::priority_queue: Priority queue.
The STL provides a wide range of algorithms that operate on sequences, such as sorting, searching, and manipulating elements.
Iterators are used to iterate through the elements of a container. They act as a generalization of pointers.
Function objects are objects that can be called as if they were functions. They are used extensively in the STL algorithms.
Allocators provide a way to customize memory management for containers.
1- Include the necessary headers:
#include <iostream>
#include <vector>
#include <algorithm>
2- Use the std namespace or prefix the STL components with std:::
using namespace std; // or use std::vector, std::sort, etc.
3- Declare and use STL containers:
vector<int> myVector = {1, 2, 3, 4, 5};
4- Apply algorithms to containers:
sort(myVector.begin(), myVector.end());
5- Utilize iterators:
for (auto it = myVector.begin(); it != myVector.end(); ++it) {
cout << *it << " ";
}
Here's a simple example that demonstrates the use of std::vector
and std::sort
:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> myVector = {5, 2, 8, 1, 3};
// Use the std::sort algorithm
std::sort(myVector.begin(), myVector.end());
// Print the sorted vector
for (int i : myVector) {
std::cout << i << " ";
}
return 0;
}
This program uses the STL to sort a vector of integers and then prints the sorted result.
The STL is a powerful and flexible library that facilitates generic programming in C++, making it easier to write efficient and maintainable code. It is a fundamental part of modern C++ programming.