0

I have the following codes trying to sort the string based the the character frequency in descending order.

string frequencySort(string s) {

    unordered_map<char,int> m{};
    for (char c:s) {
        if(m.find(c) != m.end()){
            m[c]++;
        } else {
            m[c] = 1;
        }
    }

    sort(s.begin(), s.end(), [&m](char a, char b) { return m[b] < m[a];});
    return s;
}

The code works fine, but if I use "<=" in the lambda function:

[&m](char a, char b) { return m[b] <= m[a];}

I would get heap-buffer-overflow error. Does anyone know why is that? Thanks!

Edamame
  • 20,574
  • 59
  • 165
  • 291
  • so you're saying that potentially m[b] is less than m[a] AND that m[a] is less than m[b] – UKMonkey Nov 06 '19 at 23:14
  • The `std::sort()` comparator is required to return `true` only if the 1st argument is **less than** the 2nd argument. Using ` – Remy Lebeau Nov 06 '19 at 23:15
  • @UKMonkey I am trying to say: if they are equal, I don't care about the order ... or what should be the right expression for that? – Edamame Nov 06 '19 at 23:15
  • 1
    That's a different sort of sort. std::sort doesn't care about the order for items of the same value. While stable_sort will So you need to; as remy said - adhear to the spec that says "return true if a < b" – UKMonkey Nov 06 '19 at 23:16

0 Answers0