The Standard Template Library (STL) is a powerful library in C++ that provides a set of common classes and functions for data structures and algorithms. It includes:
Containers are data structures that store collections of objects. The main types of containers in STL are:
vector
: Dynamic array.deque
: Double-ended queue.list
: Doubly linked list.set
: Collection of unique keys, sorted by keys.map
: Collection of key-value pairs, sorted by keys.multiset
: Collection of keys, allowing duplicates, sorted by keys.multimap
: Collection of key-value pairs, allowing duplicates, sorted by keys.unordered_set
: Collection of unique keys, hashed by keys.unordered_map
: Collection of key-value pairs, hashed by keys.unordered_multiset
: Collection of keys, allowing duplicates, hashed by keys.unordered_multimap
: Collection of key-value pairs, allowing duplicates, hashed by keys.Iterators are objects that point to elements in containers. They provide a way to access and traverse elements in containers.
Algorithms are functions that perform operations on containers. They are implemented as template functions and work with iterators.
find
, count
, equal
, mismatch
copy
, swap
, replace
, fill
sort
, binary_search
, lower_bound
, upper_bound
accumulate
, inner_product
, partial_sum
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec = {1, 2, 3, 4, 5};
// Display elements
for (int val : vec)
{
std::cout << val << " ";
}
std::cout << std::endl;
// Sort elements in descending order
std::sort(vec.begin(), vec.end(), std::greater<int>());
// Display sorted elements
for (int val : vec)
{
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
int main()
{
std::vector<int> vec = {1, 2, 3, 4, 5};
// Use an iterator to traverse the vector
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
{
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> vec = {1, 2, 3, 4, 5};
// Find an element
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end())
{
std::cout << "Element found: " << *it << std::endl;
}
else
{
std::cout << "Element not found" << std::endl;
}
return 0;
}
The STL is a powerful tool in C++ that provides a wide range of functionalities for managing data structures and algorithms. Understanding and utilizing STL components can greatly enhance your programming efficiency and effectiveness.