STL algorithms

10.1 - STL algorithm intro


The standard library provides a lot of useful algorithms in the <algorithm> header. The STL algorithms work with most containers like std::vector, std::array, and std::map.

The algorithms can be used with variety of containers since they utilize iterators. They work on the containers within the range [first, last), most commonly using the begin() and the end() methods on the container to get the first and last iterators.

To save time, use the built-in algorithms instead of writing your own implementation.

Task

Read the code. Run the program and see the output.

  • Press the Run button.
#include <iostream> #include <vector> #include <algorithm> std::ostream& operator<<(std::ostream &os, const std::vector<int> &v); int main() { std::vector<int> numbers{5, 2, 3, 9, 4, 0, 8, 1, 7, 6}; std::cout << "max: " << *std::max_element(numbers.begin(), numbers.end()) << std::endl; std::cout << "min: " << *std::min_element(numbers.begin(), numbers.end()) << std::endl; std::cout << "Before sort: " << numbers << std::endl; std::sort(numbers.begin(), numbers.end()); std::cout << "After sort: " << numbers << std::endl; } // Define the << for printing vector of int. std::ostream& operator<<(std::ostream &os, const std::vector<int> &v) { for (int n : v) { os << n << " "; } return os; }