C++代码中的报错, 请指教一下

2019-07-27 09:21:53 +08:00
 Akiyu
vector<string>& words;  
sort(words.begin(), words.end(), [](const string &str1, const string &str2) {  
    return str1.size() > str2.size();  
});  

我的目的是将 words 中的 string 按照长度排序 (words 中大概有 1k 个 string)

但是 lambda 函数中的比较如果是 >= 的话, 就会报错, heap buffer overflow

AddressSanitizer: heap-buffer-overflow on address 0x63000000fe08 at pc 0x000000411eff bp 0x7ffcfab095c0 sp 0x7ffcfab095b8

我的迷惑是 :

  1. 堆溢出? 怎么溢出的?

  2. 为什么 > 就可以?

903 次点击
所在节点    问与答
3 条回复
AlohaV2
2019-07-27 09:27:34 +08:00
能否再贴完整一些的代码?
richard1122
2019-07-27 09:29:30 +08:00
"Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines."

因为返回 bool 要保证 comp(a, b) 和 comp(b, a) 是只有一个 true 的,在相等时候不可以返回 true
richard1122
2019-07-27 09:30:29 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/586627

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX