上面的sort()有什么问题?我得到一个:
What is wrong with the sort() above? I am getting a:
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_allocgdb没有给我任何有用的东西...
when I call sort(). gdb isn't giving me anything useful either...
我认为这个问题与因为我在一个类中有关?
I presume the problem has something to do with cause I am in a class?
编辑:解决
问题是这一行
return a.second >= b.second;更改为
return a.second > b.second;推荐答案
std :: sort 必须建立严格弱排序。这意味着:
The comparator you give to std::sort must establish a strict weak ordering. That means:
- 对于所有x,不是compare(x,x)(irreflexivity)。
- 对于所有x≠y,如果compare(x,y),则不是compare(y,x)(不对称)。
- 对于所有x ,y和z,如果比较(x,y)和比较(y,z),则比较(x,z)(传递性)。 对于所有x,y和z ,如果x与y无法比较,并且y与z无法比较,则x与z(等价的传递性)无法比较。
- For all x, it is not the case that compare(x, x) (irreflexivity).
- For all x ≠ y, if compare(x, y) then it is not the case that compare(y, x) (asymmetric).
- For all x, y, and z, if compare(x, y) and compare(y, z) then compare(x, z) (transitivity).
- For all x, y, and z, if x is incomparable with y, and y is incomparable with z, then x is incomparable with z (transitivity of equivalence).
您的原始比较器不是无反射的: compare(x,x)是true。使用这样的比较器会导致未定义的行为,您首先遇到 std :: bad_alloc 。
Your original comparator is not irreflexive: compare(x, x) is true. Using such a comparator results in undefined behaviour, which you experienced first-hand as a std::bad_alloc.