How do I sort and stable_sort elements with std::array?

Learn how to sort and stable_sort elements using std::array in C++. This guide provides examples and explanations for sorting techniques in C++ programming.

sorting, stable_sort, std::array, C++, C++ programming, algorithms


#include <iostream>
#include <array>
#include <algorithm>

int main() {
    std::array arr = {5, 2, 3, 1, 4};

    // Sort the array
    std::sort(arr.begin(), arr.end());

    std::cout << "Sorted array: ";
    for (const auto& elem : arr) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // Stable sort example
    std::array<:pair char>, 5> stableArr = {{{5, 'e'}, {2, 'b'}, {3, 'c'}, {2, 'a'}, {4, 'd'}}};
    
    std::stable_sort(stableArr.begin(), stableArr.end(),
                     [](const auto& a, const auto& b) { return a.first < b.first; });

    std::cout << "Stable sorted array: ";
    for (const auto& elem : stableArr) {
        std::cout << "{" << elem.first << ", " << elem.second << "} ";
    }
    std::cout << std::endl;

    return 0;
}
    

sorting stable_sort std::array C++ C++ programming algorithms