Overview of commonly used <algorithm> algorithms in C++
C++ standard library<algorithm>
Header files provide a large number of useful algorithms, mainly used to operate containers (such asvector
, list
, array
wait). These algorithms usually operate container elements through iterators.
1. Non-modified sequence operations
std::all_of
, std::any_of
, std::none_of
#include <algorithm> #include <vector> std::vector<int> v = {1, 2, 3, 4, 5}; // Check whether all elements meet the conditionsbool all_even = std::all_of((), (), [](int i){ return i % 2 == 0; }); // Check whether any element meets the criteriabool any_even = std::any_of((), (), [](int i){ return i % 2 == 0; }); // Check whether no elements meet the conditionsbool none_even = std::none_of((), (), [](int i){ return i % 2 == 0; });
std::for_each
std::vector<int> v = {1, 2, 3, 4, 5}; // Perform an operation on each elementstd::for_each((), (), [](int &n){ n *= 2; });
std::count
, std::count_if
std::vector<int> v = {1, 2, 3, 4, 5}; // Calculate the number of elements equal to 3int count_3 = std::count((), (), 3); // Calculate the number of elements that meet the conditionsint count_even = std::count_if((), (), [](int i){ return i % 2 == 0; });
std::find
, std::find_if
, std::find_if_not
std::vector<int> v = {1, 2, 3, 4, 5}; // Find elements with a value of 3auto it = std::find((), (), 3); // Find the first even numberauto it_even = std::find_if((), (), [](int i){ return i % 2 == 0; }); // Find the first non-even numberauto it_not_even = std::find_if_not((), (), [](int i){ return i % 2 == 0; });
2. Modify the sequence operation
std::copy
, std::copy_if
std::vector<int> src = {1, 2, 3, 4, 5}; std::vector<int> dst(5); // Copy elementsstd::copy((), (), ()); // Conditional copystd::vector<int> dst_even; std::copy_if((), (), std::back_inserter(dst_even), [](int i){ return i % 2 == 0; });
std::fill
, std::fill_n
std::vector<int> v(5); // Fill all elements to 42std::fill((), (), 42); // Fill the first 3 elements to 10std::fill_n((), 3, 10);
std::transform
std::vector<int> v = {1, 2, 3, 4, 5}; std::vector<int> result(()); // Apply functions to each elementstd::transform((), (), (), [](int i){ return i * 2; });
std::replace
, std::replace_if
std::vector<int> v = {1, 2, 3, 4, 5}; // Replace all 3 to 10std::replace((), (), 3, 10); // Replace all even numbers to 0std::replace_if((), (), [](int i){ return i % 2 == 0; }, 0);
std::remove
, std::remove_if
std::vector<int> v = {1, 2, 3, 4, 5}; // Replace all 3 to 10std::replace((), (), 3, 10); // Replace all even numbers to 0std::replace_if((), (), [](int i){ return i % 2 == 0; }, 0);
3. Sort and related operations
std::sort
, std::stable_sort
std::vector<int> v = {5, 3, 1, 4, 2}; // Default ascending order sortstd::sort((), ()); // Custom sortingstd::sort((), (), [](int a, int b){ return a > b; }); // descending order// Stable sorting (maintain the relative order of equal elements)std::stable_sort((), ());
std::partial_sort
std::vector<int> v = {5, 6, 1, 3, 2, 4}; // Partial sorting (first 3 smallest elements)std::partial_sort((), () + 3, ());
std::nth_element
std::vector<int> v = {5, 6, 1, 3, 2, 4}; // Make the nth element in the correct positionstd::nth_element((), () + 2, ()); // v[2]Now is the correct element after sorting,All the front<=it,All the behind>=it
std::is_sorted
, std::is_sorted_until
std::vector<int> v = {1, 2, 3, 4, 5}; // Check whether it has been sortedbool sorted = std::is_sorted((), ()); // Find the first element that destroys the sortauto it = std::is_sorted_until((), ());
4. Binary search (must be used on sorted sequences)
std::lower_bound
, std::upper_bound
, std::equal_range
std::vector<int> v = {1, 2, 2, 3, 4, 5}; // Find the first element not less than 3auto low = std::lower_bound((), (), 3); // Find the first element greater than 3auto up = std::upper_bound((), (), 3); // Find ranges equal to 3auto range = std::equal_range((), (), 3);
std::binary_search
std::vector<int> v = {1, 2, 3, 4, 5}; // Check if the element existsbool found = std::binary_search((), (), 3);
5. Collection operation (must be used on sorted sequences)
std::merge
std::vector<int> v1 = {1, 3, 5}; std::vector<int> v2 = {2, 4, 6}; std::vector<int> dst(() + ()); // Merge two sorted sequencesstd::merge((), (), (), (), ());
std::includes
, std::set_difference
, std::set_intersection
, std::set_union
, std::set_symmetric_difference
std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {2, 4, 6}; std::vector<int> result; // Check whether v1 contains all elements of v2bool includes = std::includes((), (), (), ()); // Difference set (v1 - v2)std::set_difference((), (), (), (), std::back_inserter(result)); // Intersection(); std::set_intersection((), (), (), (), std::back_inserter(result)); // Converge(); std::set_union((), (), (), (), std::back_inserter(result)); // Symmetrical difference set (in v1 or v2 but not in both)(); std::set_symmetric_difference((), (), (), (), std::back_inserter(result));
6. Heap operation
std::make_heap
, std::push_heap
, std::pop_heap
, std::sort_heap
std::vector<int> v = {3, 1, 4, 1, 5, 9}; // Build the largest heapstd::make_heap((), ()); // Add elements to the heapv.push_back(6); std::push_heap((), ()); // Remove the heap top elementstd::pop_heap((), ()); v.pop_back(); // Heap sortingstd::sort_heap((), ());
7. Minimum/maximum operation
std::min_element
, std::max_element
, std::minmax_element
std::vector<int> v = {3, 1, 4, 1, 5, 9}; // Find the smallest elementauto min_it = std::min_element((), ()); // Find the largest elementauto max_it = std::max_element((), ()); // Find the smallest and largest elements at the same timeauto minmax = std::minmax_element((), ());
std::clamp
(C++17)
int value = 15; // Limit the value to the range of 10-20int clamped = std::clamp(value, 10, 20); // Return to 15clamped = std::clamp(5, 10, 20); // Return 10clamped = std::clamp(25, 10, 20); // return20
8. Arrange operations
std::next_permutation
, std::prev_permutation
std::vector<int> v = {1, 2, 3}; // Generate the next permutationdo { // Process the current arrangement} while (std::next_permutation((), ())); // Generate the previous arrangementstd::prev_permutation((), ());
9. Other useful algorithms
std::accumulate
(From<numeric>
)
#include <numeric> std::vector<int> v = {1, 2, 3, 4, 5}; //Sumint sum = std::accumulate((), (), 0); // Custom operations (such as product)int product = std::accumulate((), (), 1, [](int a, int b){ return a * b; });
std::inner_product
(From<numeric>
)
std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {4, 5, 6}; // Dot productint dot = std::inner_product((), (), (), 0);
std::iota
(From<numeric>
)
std::vector<int> v(5); // Fill in sequence valuesstd::iota((), (), 10); // v = {10, 11, 12, 13, 14}
These algorithms can greatly improve C++ programming efficiency, avoid the tedious work of manually writing loops, and are usually more efficient than handwritten loops.
This is the article about the summary of the header file algorithm in the C++ standard library. For more related C++ <algorithm> header file algorithm content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!