c++ sort vector
To sort a vector in C++, you can use the sort()
function from the <algorithm>
library. Here are the steps to sort a vector in C++:
- Include the necessary header files:
#include <vector>
#include <algorithm>
- Create a vector:
std::vector<int> myVector = {4, 2, 6, 1, 3};
- Sort the vector using the
sort()
function:
std::sort(myVector.begin(), myVector.end());
- After the
sort()
function is called, the vector will be sorted in ascending order. If you want to sort it in descending order, you can pass an additional argument tosort()
, specifying the comparison function:
std::sort(myVector.begin(), myVector.end(), std::greater<int>());
That's it! The vector is now sorted. You can access the elements of the vector using a loop or by using the std::vector
functions.