Reputation: 1
I have to sort strings by their length. Eg:
Input: "Keep calm and code on"
Expected Output: "On and keep calm code"
First Comparator is: return s1.length()<=s2.length();
Output : "On and code calm keep"
Second Comparator is : return s1.length()<s2.length();
Output : "On and keep calm code"
How output changes with change of equality in both comparators. I am confused how comparator function works internally.
Upvotes: 0
Views: 67
Reputation: 1288
use std::stable_sort. It doesn't change order of equal elements.
std::vector<std::string> vec = { "Keep" , "calm", "and", "code", "on" };
std::stable_sort(vec.begin(), vec.end(), [](const std::string& s1, const std::string& s2) { return s1.size() < s2.size(); });
for (const auto& v : vec) {
std::cout << v << std::endl;
}
Output:
on
and
Keep
calm
code
Upvotes: 3