0
0
CppHow-ToBeginner · 3 min read

How to Use sort in C++: Syntax and Examples

In C++, you use std::sort from the <algorithm> header to sort elements in a container like an array or vector. Call std::sort(begin, end) to sort in ascending order, or provide a custom comparison function for other orders.
📐

Syntax

The basic syntax of std::sort is:

  • std::sort(start, end); - sorts elements from start to end in ascending order.
  • std::sort(start, end, comp); - sorts using a custom comparison function comp.

Here, start and end are iterators pointing to the beginning and one past the last element of the range to sort.

cpp
#include <algorithm>
#include <vector>

// Sort in ascending order
std::sort(container.begin(), container.end());

// Sort with custom comparator
std::sort(container.begin(), container.end(), comp);
💻

Example

This example shows how to sort a vector of integers in ascending order using std::sort.

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

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
    std::sort(numbers.begin(), numbers.end());

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output
1 2 5 5 6 9
⚠️

Common Pitfalls

Common mistakes when using std::sort include:

  • Not including the <algorithm> header.
  • Passing pointers or iterators incorrectly (e.g., forgetting that end is one past the last element).
  • Trying to sort containers that do not support random access iterators (like std::list).
  • Using a wrong comparator that does not define a strict weak ordering.
cpp
#include <algorithm>
#include <vector>

// Wrong: sorting a list (does not support random access iterators)
// std::list<int> lst = {3,1,2};
// std::sort(lst.begin(), lst.end()); // Error

// Correct: use vector or array
std::vector<int> vec = {3,1,2};
std::sort(vec.begin(), vec.end());
📊

Quick Reference

std::sort quick tips:

  • Include <algorithm>.
  • Use with containers supporting random access iterators (e.g., std::vector, arrays).
  • Syntax: std::sort(begin, end); for ascending order.
  • For descending order: std::sort(begin, end, std::greater<Type>());
  • Custom comparator must return true if first argument should go before second.

Key Takeaways

Use std::sort from to sort containers with random access iterators.
Call std::sort with begin and end iterators to sort in ascending order by default.
Provide a custom comparator to change the sorting order or criteria.
Do not use std::sort on containers like std::list that lack random access iterators.
Remember to include and pass iterators correctly.