The C++ Standard Library provides a wide range of algorithms that can be used to manipulate and process sequences of data. These algorithms are designed to be efficient and easy to use.
Common Algorithms
- Sort:
std::sort
is used to sort a range of elements.std::sort(v.begin(), v.end());
- Search:
std::find
is used to find an element in a range.auto it = std::find(v.begin(), v.end(), value);
- Copy:
std::copy
is used to copy elements from one range to another.std::copy(v.begin(), v.end(), back_inserter(target));
- Transform:
std::transform
is used to transform elements in a range.std::transform(v.begin(), v.end(), back_inserter(target), [](int x) { return x * 2; });
Algorithm Examples
Here are some examples of how algorithms can be used in practice:
Sorting a Vector:
std::vector<int> v = {4, 1, 3, 9, 7}; std::sort(v.begin(), v.end());
Finding an Element:
std::vector<int> v = {1, 2, 3, 4, 5}; auto it = std::find(v.begin(), v.end(), 3); if (it != v.end()) { std::cout << "Element found: " << *it << std::endl; } else { std::cout << "Element not found" << std::endl; }
Copying Elements:
std::vector<int> v = {1, 2, 3, 4, 5}; std::vector<int> target; std::copy(v.begin(), v.end(), back_inserter(target));
Transforming Elements:
std::vector<int> v = {1, 2, 3, 4, 5}; std::vector<int> target; std::transform(v.begin(), v.end(), back_inserter(target), [](int x) { return x * 2; });
Learn More
For more information on the C++ Standard Library algorithms, visit our C++ Standard Library Reference.
Algorithm Flowchart