In this C++ tutorial, you shall learn how to sort a given vector using std::sort() function, with example programs.

Sort a Vector

To sort a vector in C++, we can use std::sort() method of algorithm library.

Import algorithm library, call sort() method, and pass the beginning and ending of the vector as arguments to the method. The method sorts the vector in-place, i.e., the original vector is updated.

The syntax of the statement to sort a vector v is

//include algorithm
#include <algorithm>

//call sort method
std::sort(v.begin(), v.end());

C++ Program

In the following program, we take an integer vector in v, and reverse it using reverse() method.


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
   vector<int> v { 4, 0, 2, 1, 8, 7, 3 };
   sort(v.begin(), v.end());

   for(auto& element: v) {
      cout << element << "  ";


0  1  2  3  4  7  8


In this C++ Tutorial, we learned how to sort a vector using std::sort() method of algorithm library.