Introduction to STL and its Components in C++
The Standard Template Library (STL) is a powerful feature of C++ that provides a set of common data structures and algorithms. It enables programmers to use pre-defined classes and functions to handle collections of data effectively, saving time and effort.
What is STL?
STL stands for Standard Template Library, and it is a collection of template classes and functions. It provides four major components:
- Containers
- Iterators
- Algorithms
- Functors
Components of STL
1. Containers
Containers are data structures that store data. They are classified into three types:
- Sequence Containers: These store data in a linear sequence. Examples:
vector,list,deque. - Associative Containers: These store data in a sorted order. Examples:
set,map. - Unordered Containers: These store data in an unordered fashion. Examples:
unordered_set,unordered_map.
Example of vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << num << " ";
}
return 0;
}
2. Iterators
Iterators are used to traverse elements in a container. They work like pointers to access the elements.
Example of an iterator with vector:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector numbers = {10, 20, 30};
vector::iterator it;
for (it = numbers.begin(); it != numbers.end(); ++it) {
cout << *it << " ";
}
return 0;
}
3. Algorithms
Algorithms are a set of functions for operations such as searching, sorting, and manipulating data.
Example of sort():
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector numbers = {40, 10, 20, 30};
sort(numbers.begin(), numbers.end());
for (int num : numbers) {
cout << num << " ";
}
return 0;
}
4. Functors
Functors are objects that can be used as functions. They are implemented using operator overloading.
Example of a functor:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct MultiplyByTwo {
void operator()(int &x) {
x *= 2;
}
};
int main() {
vector numbers = {1, 2, 3};
for_each(numbers.begin(), numbers.end(), MultiplyByTwo());
for (int num : numbers) {
cout << num << " ";
}
return 0;
}
Conclusion
STL is an essential part of C++ programming, offering a wide range of pre-built functionalities. Understanding its components like containers, iterators, algorithms, and functors helps developers write efficient and maintainable code.