You can sort a vector in ascending or descending order of the value of elements, or use a custom function to sort the vector based on the derived values of the existing elements.

In this C++ tutorial, you shall learn how to sort a given vector using std::sort() function template of the <algorithm> library, with detailed programs.

Syntax of std::sort

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

The syntax to sort a given vector in ascending order, descending order, or use a custom comparison function is given below.

</>
Copy
// Sort in ascending order
std::sort(vector.begin(), vector.end());

// Sort in descending order
std::sort(vector.begin(), vector.end(), std::greater<int>());

// Sort using a custom comparison function
std::sort(vector.begin(), vector.end(), customComparisonFunction);

Sorting a Vector in Ascending Order

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

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> myvector = {32, 71, 12, 45, 26, 80, 53, 33};

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

    std::cout << "Vector sorted in ascending order:";
    for (const auto& elem : myvector)
        std::cout << ' ' << elem;
    std::cout << std::endl;

    return 0;
}

Output:

Vector sorted in ascending order: 12 26 32 33 45 53 71 80

Explanation:

  1. Initialize the vector: A std::vector named myvector is created and initialized with the values {32, 71, 12, 45, 26, 80, 53, 33}. This vector contains unsorted integers to demonstrate sorting in ascending order.
  2. Sort the vector in ascending order: The std::sort function is called with the following arguments:
    • myvector.begin(): Specifies the starting point of the range to be sorted.
    • myvector.end(): Specifies the end of the range to be sorted.
    std::sort sorts the elements in ascending order using the default comparison operator (<).
  3. Print the sorted vector: A range-based for loop iterates over the sorted vector. Each element is printed to the console using std::cout, separated by spaces. The message "Vector sorted in ascending order:" is printed before the elements.

Sorting a Vector in Descending Order

In this example, we will sort a vector of integers in descending order using the std::greater<> comparator.

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> myvector = {32, 71, 12, 45, 26, 80, 53, 33};

    // Sort in descending order
    std::sort(myvector.begin(), myvector.end(), std::greater<int>());

    std::cout << "Vector sorted in descending order:";
    for (const auto& elem : myvector)
        std::cout << ' ' << elem;
    std::cout << std::endl;

    return 0;
}

Output:

Vector sorted in descending order: 80 71 53 45 33 32 26 12

Explanation:

  1. Sorting the vector in descending order: The std::sort function is called with three arguments:
    • myvector.begin(): Specifies the starting point of the range to be sorted.
    • myvector.end(): Specifies the end of the range to be sorted.
    • std::greater<int>(): A comparator provided by the STL that sorts the elements in descending order.
    std::greater<int>() compares two elements and ensures the larger one appears earlier in the sorted range.

Sorting a Vector Using a Custom Comparison Function

This example demonstrates sorting a vector of integers where even numbers are placed before odd numbers, sorted within their groups.

</>
Copy
#include <iostream>
#include <algorithm>
#include <vector>

// Custom comparison function: even numbers first
bool customComparison(int i, int j) {
    if ((i % 2 == 0) && (j % 2 != 0)) return true; // Even comes before odd
    if ((i % 2 != 0) && (j % 2 == 0)) return false; // Odd comes after even
    return i < j; // Sort within groups
}

int main() {
    std::vector<int> myvector = {32, 71, 12, 45, 26, 80, 53, 33};

    // Sort using custom comparison function
    std::sort(myvector.begin(), myvector.end(), customComparison);

    std::cout << "Vector sorted with custom comparison:";
    for (const auto& elem : myvector)
        std::cout << ' ' << elem;
    std::cout << std::endl;

    return 0;
}

Output:

Vector sorted with custom comparison: 12 26 32 80 33 45 53 71

Explanation:

  1. Define a custom comparison function: The function customComparison is defined to sort the elements of the vector based on the following rules:
    • Even numbers are prioritized to appear before odd numbers.
    • If both numbers are even or both are odd, they are sorted in ascending order.
    • For example:
      • If i = 32 and j = 71, the function returns true because 32 is even and 71 is odd.
      • If both i and j are even, it compares their values and sorts them in ascending order.
  2. Sort the vector with the custom comparison function: The std::sort function is called with three arguments:
    • myvector.begin(): Specifies the starting point of the range to be sorted.
    • myvector.end(): Specifies the end of the range to be sorted.
    • customComparison: The custom comparison function that determines the sorting order.
    The elements are rearranged such that even numbers are placed before odd numbers, and within each group, the numbers are sorted in ascending order.

Conclusion

Using std::sort, you can sort vectors in ascending or descending order easily and customize the sorting logic with a comparator function.