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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?