[英]Segfault from using std::sort on vector<pair<string, int>>
I am writing a c++ program that counts occurrence of distinct strings in a given file. 我正在编写一个c ++程序,该程序计算给定文件中不同字符串的出现。 I use std::sort to sort it in descending order of the second field (int).
我使用std :: sort对第二个字段(int)的降序进行排序。
...
bool compare(const std::pair<std::string, int> &p1, const std::pair<std::string, int> &p2) {
if (p1.second < p2.second) return false;
return true;
}
TC::TC(const std::vector<std::string> &collection) {
...
// iterating through collection with iterator "it", and push_back a pair when unique string found
std::pair<std::string, int> temp = {*it, std::count(collection.begin(), collection.end(), *it)};
counts.push_back(temp);
// calling std::sort to sort descending order of the field "second"
std::sort(counts.begin(), counts.end(), &compare);
Yet, when I test on a sample file (that I can pass as an argument to main), I get segfault. 但是,当我在示例文件上进行测试(我可以将其作为参数传递给main)时,会遇到段错误。 And, from looking into gdb, following shows up:
并且,通过查看gdb,将显示以下内容:
47 if (p1.second < p2.second) {
(gdb) p p1
$14 = (const std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> &) @0x61c520: {first = "namespace", second = 1}
...
(gdb) p p1
$16 = (const std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> &) @0x61c500: {first = {static npos = <optimized out>,
_M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x61ec88 "sep"}}, second = 1}
It appears to me that the field "first" of some pairs went out of scope and became garbage if I am interpreting that "<__gnu_css..... _M_p" correctly. 在我看来,如果我正确地解释为“ <__ gnu_css ..... _M_p”,则某些对中的“第一”字段将超出范围并变为垃圾。 However, I am confused why such would happen since push_back will create a new copy of pair of new string and int.
但是,我很困惑为什么会这样,因为push_back将创建一对新字符串和整数的新副本。 So it should not be garbage.
所以它不应该是垃圾。 This is my first post and I am still novice in c++, so please let me know if anything doesn't seem clear.
这是我的第一篇文章,我仍然是C ++的新手,所以如果有任何不清楚的地方,请告诉我。
compare
is somehow messed up and doesn't meet the requirements of Compare
. compare
被搞砸了,不符合Compare
的要求。 Throw away the branching and simply do: 扔掉分支,然后简单地执行以下操作:
return p1.second > p2.second;
to sort in descending order. 以降序排列。 What you have is essentially a
>=
, which violates: 您所拥有的基本上是一个
>=
,它违反了:
- For all
a
,comp(a,a)==false
对于所有
a
,comp(a,a)==false
- If
comp(a,b)==true
thencomp(b,a)==false
如果
comp(a,b)==true
则comp(b,a)==false
and this results in undefined behavior. 这会导致不确定的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.