In C++, you can sort and stable_sort elements within a std::deque using the standard sorting algorithms provided by the C++ Standard Library. The std::sort
function is a non-stable sort, while std::stable_sort
maintains the relative order of equivalent elements.
Here's an example demonstrating how to use both std::sort
and std::stable_sort
with a std::deque
:
#include <iostream>
#include <deque>
#include <algorithm>
int main() {
std::deque dq = { 5, 2, 8, 3, 5, 1 };
// Using std::sort (non-stable)
std::sort(dq.begin(), dq.end());
std::cout << "Sorted with std::sort: ";
for (int n : dq) {
std::cout << n << " ";
}
std::cout << std::endl;
std::deque dq2 = { 5, 2, 8, 3, 5, 1 };
// Using std::stable_sort (stable)
std::stable_sort(dq2.begin(), dq2.end());
std::cout << "Sorted with std::stable_sort: ";
for (int n : dq2) {
std::cout << n << " ";
}
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?