gpt4 book ai didi

c++ - 错误 : malloc():memory corruption in Comparison function for sort

转载 作者:太空狗 更新时间:2023-10-29 20:37:53 24 4
gpt4 key购买 nike

以下代码用于打印整数列表中的最大数。我得到:

 *** Error in `./a.out': malloc(): memory corruption: 0x0000000000bfe070 ***

在列表中(20 个零):

 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

但是在上面,如果我放置一些非零元素,我不会得到错误。

这是我的比较函数代码:

bool comp(int a,int b)
{
if(a == b)
return true;
stringstream ss;
ss << a;
string a1 = ss.str();
stringstream sss;
sss << b;
string b1 = sss.str();
int i = 0;
int l1 = a1.length();
int l2 = b1.length();
while(i < l1 && i < l2)
{
if(a1[i] > b1[i])
return true;
if(a1[i] < b1[i])
return false;
i++;
}
if(l1 == l2)
return true;
if(l1 < l2)
if(b1[l1] > a1[0])
return false;
else
return true;
else
if(a1[l2] > b1[0])
return true;
else
return false;
}

我正在使用STL

 sort(nums.begin(),nums.end(),comp);

其中 nums 是整数 vector 。

编辑 1:

这是完整的代码:

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<sstream>

using namespace std;
bool comp(int a,int b)
{
if(a == b)
return true;
stringstream ss;
ss << a;
string a1 = ss.str();
stringstream sss;
sss << b;
string b1 = sss.str();
int i = 0;
int l1 = a1.length();
int l2 = b1.length();
while(i < l1 && i < l2)
{
if(a1[i] > b1[i])
return true;
if(a1[i] < b1[i])
return false;
i++;
}
if(l1 == l2)
return true;
if(l1 < l2)
if(b1[l1] > a1[0])
return false;
else
return true;
else
if(a1[l2] > b1[0])
return true;
else
return false;
}
void largestNumber(vector<int>& nums)
{

sort(nums.begin(),nums.end(),comp);
/*string s = "";
vector<int>::iterator it = nums.begin();
while(it != nums.end())
{
stringstream ss;
ss << *it;
s = s+ss.str();
it++;
}
return s;*/
}



int main()
{
int n;
cin>>n;
vector<int> arr(n);
for(int i = 0;i<n;i++)
cin>>arr[i];

largestNumber(arr);/*
string s = largestNumber(arr);
cout<<s<<endl;*/
}

最佳答案

您的 comp 函数违反了 strict weak ordering rule .排序要求比较函数应满足严格的弱排序规则。如果这个 promise 被打破,那么 std::sort 的 promise 也会正确运行。事实上,当我在 MSVC (VS2015) 下编译它时,我得到一个断言失败,即比较函数不满足排序条件。例如这一行:

 if(a == b)
return true;

明显违反了条件。检查this发布更多见解。

顺便说一句,如果你只想按字典顺序对整数进行排序,你可以这样做

bool comp(int a,int b)
{
return to_string(a) < to_string(b);
}

如果你想要“大数优先”的等价物,只需将 < 换成 >

关于c++ - 错误 : malloc():memory corruption in Comparison function for sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com