STL algorithms

10.2 - Sort


The std::sort(first, last) method takes the first and last iterator and sorts the elements within the range [first, last).

It works as long as the type of the compared elements has the < operator defined, which is predefined for types like int and std::string.

std::sort is sufficient for most use cases, only use your own sort function if you know you need it.

Task

Write a program which receives multiple integers, sorts them, and then prints them out.

  • Start by defining an std::vector<int> variable.
  • Use the std::cin inside a while loop condition to take the input integers.
  • Sort the vector using std::sort(v.begin(), v.end()).
  • Print out each integer in the vector.
#include <iostream> #include <vector> #include <algorithm> int main() { }