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

Sorting and stable sorting elements in a std::vector in C++ can be accomplished using the std::sort and std::stable_sort algorithms from the Standard Template Library (STL). The difference between the two is that std::stable_sort maintains the relative order of equivalent elements, whereas std::sort does not guarantee this property.

Sorting with std::sort

The std::sort function is ideal for cases where the order of identical elements does not matter.

Stable Sorting with std::stable_sort

Use std::stable_sort when you want to maintain the original order of equivalent elements.

Example Code

#include <iostream> #include <vector> #include <algorithm> int main() { std::vector numbers = {4, 1, 3, 4, 2, 5, 3}; // Using std::sort std::sort(numbers.begin(), numbers.end()); std::cout << "Sorted (std::sort): "; for (const auto &num : numbers) { std::cout << num << " "; } std::cout << std::endl; // Using std::stable_sort std::vector stable_numbers = {4, 1, 3, 4, 2, 5, 3}; std::stable_sort(stable_numbers.begin(), stable_numbers.end()); std::cout << "Sorted (std::stable_sort): "; for (const auto &num : stable_numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }

C++ STL std::vector std::sort std::stable_sort sorting algorithms C++ examples