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

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

C++ std::deque sorting stable_sort standard library algorithms