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;
}
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?