Sorting comparator in c++

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.

1 answer

  • answered 2020-07-29 17:42 akk0rd87

    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