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
  • 23,718
  • 73
  • 186
  • 320
  • 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 `<` satisfies that, but `<=` does not. Also, in your `loop`, you don't need to call `m.find()` manually at all, since `operator[]` will insert a default value (which for an `int` is 0) if the specified key is not found: `for (char c:s) { m[c]++; }` (besides, you are not using the iterator returned by `find()` effectively anyway, calling `operator[]` does the same search that `find()` does, so you may as well just remove the `find()`) – 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