C++ STL Tutorial: Algorithm
C++ Standard Template Library provides a collection of algorithms that can be used to perform common tasks on containers like vectors, lists, arrays, etc. The algorithms are implemented as functions and can be used to sort, search, and manipulate container elements.
Syntax
The syntax for using an algorithm is as follows:
#include <algorithm>
// Algorithm function
algorithm_name(container.begin(), container.end(), function);
Where algorithm_name is the name of the algorithm, container is the name of the container being operated on, and function is a function object that defines the operation to be performed.
Example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
// Declare a vector of integers
vector<int> v = {5, 3, 1, 7, 9};
// Sort the vector elements in ascending order
sort(v.begin(), v.end());
// Print the sorted elements
for (auto i : v) {
cout << i << " ";
}
cout << endl;
// Find the first occurrence of 7 in the vector
auto it = find(v.begin(), v.end(), 7);
// Print the value of the found element
if (it != v.end()) {
cout << "Found " << *it << endl;
}
else {
cout << "Element not found" << endl;
}
return 0;
}
Output
1 3 5 7 9
Found 7
Explanation
In the above example, we first declare a vector of integers and initialize it with some values. We then use the sort()
algorithm to sort the elements in ascending order. We then use the find()
algorithm to find the first occurrence of the element 7
in the vector. If the element is found, we print its value, otherwise we print a message indicating that the element was not found.
Use
Algorithms in the C++ STL can be used to perform common tasks on containers with ease. They can be used to sort, search, and manipulate container elements without having to write complicated code.
Commonly used algorithms include sort()
, find()
, find_if()
, copy()
, reverse()
, replace()
, unique()
, shuffle()
, and many more.
Important Points
- C++ STL provides a collection of algorithms for performing common tasks on containers.
- Algorithms are implemented as functions.
- Most algorithms take a range of iterators as parameters.
- Algorithms can be used to sort, search, and manipulate container elements.
Summary
In summary, the C++ STL provides a vast collection of algorithms that can be used to work with containers. Algorithms are easy to use and can be used to perform many common tasks, saving time and effort. Understanding the basic algorithms is an important part of mastering the C++ language.