struct Item {
int id;
int value;
};
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<Item> items = {{1, 5}, {2, 3}, {3, 5}, {4, 2}};
std::stable_sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
return a.value < b.value;
});
for (const auto& item : items) {
std::cout << item.id << "-" << item.value << " ";
}
return 0;
}The stable sort arranges items by their 'value' in ascending order. For items with the same 'value', their original order is preserved. Here, items with value 5 are {1,5} then {3,5}, so they remain in that order after sorting.
Stable sorts keep the original order of equal elements, which is important when the order carries meaning, such as sorting by multiple keys in sequence.
struct Item {
int id;
int value;
};
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<Item> items = {{1, 5}, {2, 3}, {3, 5}, {4, 2}};
std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) {
return a.value < b.value;
});
for (const auto& item : items) {
std::cout << item.id << "-" << item.value << " ";
}
return 0;
}std::sort is not guaranteed to be stable, so items with equal 'value' may appear in any order. One possible output is with the two items of value 5 swapped.
Sorting multiple keys by repeated stable sorts from least to most important key preserves the order of previous keys, achieving a multi-key sort.
std::vector<std::pair<int,int>> v = {{1,2}, {2,1}, {3,2}, {4,1}}; std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second < b.second; }); for (auto& p : v) { std::cout << "(" << p.first << "," << p.second << ") "; }
std::sort is not stable, so it does not guarantee to keep the original order of elements with equal keys. To preserve order, std::stable_sort should be used.