What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More
Computer Science

Sort a Vector in C++ (Ascending, Descending, and 2D)

Jul 19, 2026 6 Minutes Read Why Trust Us Why you can trust this guide. Written by working engineers and reviewed by our editorial team under a strict editorial policy for accuracy, clarity and zero bias. Anubhav Agarwal By Anubhav Agarwal Anubhav Agarwal Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.
Connect on LinkedIn →
Sort a Vector in C++ (Ascending, Descending, and 2D)

In C++, you sort a vector with the std::sort() function from the <algorithm> header: sort(v.begin(), v.end()) arranges the elements in ascending order in place.

The same function sorts in descending order with a comparator, sorts by a custom rule with a lambda, and sorts a 2D vector row by row. This lesson shows each form with runnable code and the complexity to expect.

How Do You Sort a Vector in C++?

Call std::sort() with the vector's begin() and end() iterators, and the elements are rearranged in ascending order.

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

int main() {
    vector<int> ages = {34, 19, 27, 42};

    sort(ages.begin(), ages.end());

    for (int age : ages) cout << age << " ";
    // Output: 19 27 34 42
    return 0;
}

sort() modifies the vector itself and returns nothing. It runs in O(N log N) time, meaning the work grows only a little faster than the number of elements.

std::sort arranging a C++ vector in ascending order and greater<int>() arranging it in descending order

How to Sort a Vector in C++

1) Ascending Order with std::sort()

The default comparison is <, so numbers go from smallest to largest and strings go alphabetically.

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

int main() {
    vector<string> cities = {"tokyo", "berlin", "quito", "cairo"};

    sort(cities.begin(), cities.end());

    for (const string& city : cities) cout << city << " ";
    // Output: berlin cairo quito tokyo
    return 0;
}

2) Descending Order with greater<>()

Pass greater<int>() from the <functional> header as the third argument to reverse the comparison.

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

int main() {
    vector<int> scores = {88, 95, 72, 91};

    sort(scores.begin(), scores.end(), greater<int>());

    for (int s : scores) cout << s << " ";
    // Output: 95 91 88 72
    return 0;
}

3) A Custom Order with a Lambda

A lambda comparator defines any ordering rule. It receives two elements and returns true when the first should come before the second.

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

int main() {
    vector<string> tags = {"backend", "ui", "devops", "api"};

    sort(tags.begin(), tags.end(), [](const string& a, const string& b) {
        return a.size() < b.size();
    });

    for (const string& tag : tags) cout << tag << " ";
    // Output: ui api devops backend
    return 0;
}

The comparator must be strict: return false for equal elements. Using <= instead of < causes undefined behavior.

How to Sort a Vector in Descending Order in C++

Two forms produce a descending sort. greater<int>() states the intent directly, and reverse iterators (rbegin()/rend()) sort the reversed view, which ends with the same result.

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

int main() {
    vector<double> prices = {24.50, 89.99, 12.75, 219.00};

    sort(prices.rbegin(), prices.rend());

    for (double p : prices) cout << p << " ";
    // Output: 219 89.99 24.5 12.75
    return 0;
}

How to Sort a 2D Vector in C++

Sorting a vector of vectors compares whole rows. By default rows compare element by element from the left, so the sort orders them by first column, then second, and so on.

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

int main() {
    vector<vector<int>> points = {{3, 40}, {1, 90}, {3, 10}};

    sort(points.begin(), points.end());

    for (const auto& p : points) cout << "{" << p[0] << "," << p[1] << "} ";
    // Output: {1,90} {3,10} {3,40}
    return 0;
}

To sort by a specific column, use a lambda that compares that column only.

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

int main() {
    vector<vector<int>> jobs = {{101, 5}, {102, 2}, {103, 9}};

    sort(jobs.begin(), jobs.end(), [](const vector<int>& a, const vector<int>& b) {
        return a[1] < b[1];
    });

    for (const auto& j : jobs) cout << j[0] << " ";
    // Output: 102 101 103
    return 0;
}
A 2D vector in C++ sorted by its second column using a lambda comparator

When to Use Each Form

FormUse it when
sort(v.begin(), v.end())Ascending order with the default <
sort(v.begin(), v.end(), greater<int>())Descending order, stated explicitly
sort(v.rbegin(), v.rend())Descending order without <functional>
Lambda comparatorSorting by length, by a field, or by one column
stable_sort()Equal elements must keep their original order

Examples of Sorting a Vector in C++

1) Sorting a Vector of Pairs

Pairs compare by first, then second, so a vector of (score, name) pairs sorts by score without a comparator.

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

int main() {
    vector<pair<int, string>> results = {{91, "lena"}, {78, "marco"}, {91, "amir"}};

    sort(results.begin(), results.end());

    for (const auto& r : results) cout << r.second << " ";
    // Output: marco amir lena
    return 0;
}

2) Top Three Values Only

partial_sort() orders just the first part of the vector, which is cheaper than sorting everything when only the top few matter.

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

int main() {
    vector<int> downloads = {320, 1750, 640, 2210, 980};

    partial_sort(downloads.begin(), downloads.begin() + 3, downloads.end(), greater<int>());

    for (int i = 0; i < 3; i++) cout << downloads[i] << " ";
    // Output: 2210 1750 980
    return 0;
}

3) Keeping Ties in Order with stable_sort()

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

int main() {
    vector<pair<string, int>> queue = {{"ana", 2}, {"raj", 1}, {"tom", 2}, {"liu", 1}};

    stable_sort(queue.begin(), queue.end(), [](const auto& a, const auto& b) {
        return a.second < b.second;
    });

    for (const auto& q : queue) cout << q.first << " ";
    // Output: raj liu ana tom
    return 0;
}

stable_sort() keeps raj before liu and ana before tom because that was their original order. Plain sort() gives no such guarantee for ties.

Learn More About Sorting Vectors

The Complexity of std::sort()

std::sort() is required to run in O(N log N) comparisons. Implementations typically use introsort, a mix of quicksort, heapsort, and insertion sort. stable_sort() may use extra memory to preserve the order of equal elements.

Checking If a Vector Is Sorted

is_sorted(v.begin(), v.end()) returns true when the elements are already in order, in a single O(N) pass.

Sorting Part of a Vector

sort() accepts any iterator range, so sort(v.begin() + 1, v.end()) leaves the first element in place and sorts the rest.

Sort a Vector in C

C has no vectors, but its arrays sort with qsort() from <stdlib.h>, which takes the array, its length, the element size, and a comparison function returning negative, zero, or positive.

Key Takeaways for Sorting a Vector in C++

  • std::sort() - sorts in place in ascending order; include <algorithm>.
  • Descending - pass greater<int>() or sort the rbegin()/rend() range.
  • Lambdas - define any rule; the comparator must return false for equal elements.
  • 2D vectors - rows sort by first column by default, or by any column with a lambda.
  • Cost - O(N log N) time; partial_sort() is cheaper when only the top few elements matter.

Sorting assumes the vector already holds its data. For the ways to declare and fill one, read our lesson on initializing a vector in C++.

Anubhav Agarwal
About the author

Anubhav Agarwal

I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for. Connect on LinkedIn →