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.
The std::sort
function is ideal for cases where the order of identical elements does not matter.
Use std::stable_sort
when you want to maintain the original order of equivalent elements.
#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;
}
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?