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

Sorting and stable sorting elements with std::span in C++ can be efficiently accomplished with the standard algorithms provided by the C++ Standard Library. Below, you will find an example of how to use std::sort and std::stable_sort with a std::span to organize elements in a container.

#include <iostream> #include <algorithm> #include <span> #include <vector> int main() { std::vector<int> vec = {5, 1, 4, 3, 2}; std::span<int> span(vec); // Creating a span from the vector // Using std::sort to sort the elements std::sort(span.begin(), span.end()); std::cout << "Sorted elements: "; for (int num : span) std::cout << num << " "; std::cout << std::endl; // Using std::stable_sort to sort the elements std::vector<std::pair<int, char>> stableVec = {{5, 'e'}, {1, 'a'}, {4, 'd'}, {3, 'c'}, {2, 'b'}}; std::span<std::pair<int, char>> stableSpan(stableVec); std::stable_sort(stableSpan.begin(), stableSpan.end(), [](const auto &a, const auto &b) { return a.first < b.first; // Sorting by the first element of the pair }); std::cout << "Stable sorted elements: "; for (const auto &p : stableSpan) std::cout << "{" << p.first << ", " << p.second << "} "; std::cout << std::endl; return 0; }

C++ std::span std::sort std::stable_sort sorting algorithms C++ Standard Library programming tutorials