How to Sort Vector in C++: Syntax and Examples
To sort a
std::vector in C++, use the std::sort function from the <algorithm> header. Call std::sort with the vector's begin() and end() iterators to sort elements in ascending order.Syntax
The basic syntax to sort a vector v is:
std::sort(v.begin(), v.end());sorts in ascending order.- You can provide a custom comparison function for other orders.
Explanation:
std::sort: Function that sorts elements.v.begin(): Iterator to the first element.v.end(): Iterator just past the last element.
cpp
std::sort(v.begin(), v.end());
Example
This example shows how to sort a vector of integers in ascending order and print the result.
cpp
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {5, 2, 9, 1, 5, 6}; std::sort(v.begin(), v.end()); for (int num : v) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
1 2 5 5 6 9
Common Pitfalls
Common mistakes when sorting vectors include:
- Not including the
<algorithm>header, which causes compilation errors. - Passing the vector itself instead of iterators to
std::sort. - Trying to sort vectors of non-comparable types without a custom comparator.
Wrong:
std::sort(v); // Error: expects iterators, not vector
Right:
std::sort(v.begin(), v.end());
cpp
/* Wrong way - causes compilation error */ // std::sort(v); // Uncommenting this line will cause error /* Right way */ std::sort(v.begin(), v.end());
Quick Reference
| Operation | Code Example | Description |
|---|---|---|
| Sort ascending | std::sort(v.begin(), v.end()); | Sorts vector elements from smallest to largest |
| Sort descending | std::sort(v.begin(), v.end(), std::greater<>()); | Sorts vector elements from largest to smallest |
| Custom sort | std::sort(v.begin(), v.end(), [](int a, int b){ return a % 10 < b % 10; }); | Sorts by last digit using a lambda function |
Key Takeaways
Use std::sort with vector's begin() and end() iterators to sort elements.
Include header to access std::sort function.
Pass a custom comparator to std::sort for descending or custom order.
Do not pass the vector itself to std::sort; always use iterators.
Sorting works only if elements are comparable or a comparator is provided.