C++ sort()

Introduction

For example, if we want to sort our container, we can use the std::sort function.

To sort our vector in ascending order, we use:

#include <iostream> 
#include <vector> 
#include <algorithm> 

int main() /*from   w ww . j  a  v a2s  .co  m*/
{ 
    std::vector<int> v = { 1, 5, 2, 15, 3, 10 }; 
    std::sort(v.begin(), v.end()); 

    for (auto el : v) 
    { 
        std::cout << el << '\n'; 
    } 
} 

The std::sort function sorts a range of elements.

It accepts arguments representing the start and the end of the range (one past the end of the range, to be exact).

Here we passed in the entire vector's range, where v.begin() represents the beginning and v.end() represents one past the end of the range.

To sort a container in descending order, we pass in an additional argument called a comparator.




PreviousNext

Related