<algorithm>
The <algorithm>
header is a fundamental part of the C++ Standard Library. It provides a collection of functions designed to perform algorithmic operations on ranges of elements. These algorithms are highly optimized and can significantly simplify common programming tasks, making your code more efficient and readable.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {5, 2, 8, 1, 9, 3};
std::sort(numbers.begin(), numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::sort
to sort a vector of integers in ascending order#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto it = std::find(numbers.begin(), numbers.end(), 7);
if (it != numbers.end()) {
std::cout << "Found 7 at position: " << std::distance(numbers.begin(), it) << std::endl;
} else {
std::cout << "7 not found in the vector" << std::endl;
}
return 0;
}
std::find
to search for an element in a containerstd::distance
to compute the position of the found element#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::vector<int> squared(numbers.size());
std::transform(numbers.begin(), numbers.end(), squared.begin(),
[](int x) { return x * x; });
for (int num : squared) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::transform
to apply a transformation to each element of a container#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
numbers.erase(std::remove_if(numbers.begin(), numbers.end(),
[](int x) { return x % 2 == 0; }),
numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
std::remove_if
and vector::erase
<algorithm>
have parallel execution policies available in C++17 and later, allowing for easy parallelization of operationsstd::set
or std::map
), consider using their member functions instead of algorithms from <algorithm>
for better performanceThe <algorithm>
header is a powerful tool in the C++ Standard Library that provides a wide range of algorithms for working with containers and ranges of elements. It includes functions for sorting, searching, modifying, and transforming data, among many others. By leveraging these algorithms, developers can write more concise, efficient, and readable code.
These examples showcase the versatility and ease of use of the algorithms provided by <algorithm>
. By mastering these algorithms, C++ developers can significantly improve their productivity and code quality.