错误:malloc():用于排序的比较函数中的内存损坏

mid*_*idi 3 c++ stl

以下代码用于打印整数列表中的最大数字.我正进入(状态:

 *** Error in `./a.out': malloc(): memory corruption: 0x0000000000bfe070 ***
Run Code Online (Sandbox Code Playgroud)

在列表中(20个零):

 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Run Code Online (Sandbox Code Playgroud)

但是在上面,如果我把一些非零元素我没有得到错误.

这是我的比较函数代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用stl

 sort(nums.begin(),nums.end(),comp);
Run Code Online (Sandbox Code Playgroud)

其中nums是整数的向量.

编辑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;*/
}
Run Code Online (Sandbox Code Playgroud)

bas*_*hrc 6

你的comp函数违反了严格的弱排序规则.排序要求比较函数应满足严格的弱排序规则.如果该承诺被破坏,那么std :: sort的承诺也是正确的.事实上当我在MSVC(VS2015)下编译它时,我得到一个断言失败,即比较函数不符合排序条件.例如这条线:

 if(a == b)
     return true;
Run Code Online (Sandbox Code Playgroud)

显然违反了这个条件.查看帖子以获取更多见解.

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

bool comp(int a,int b)
{
    return to_string(a) < to_string(b);
}
Run Code Online (Sandbox Code Playgroud)

如果你想要相当于"更大的数字第一",只需交换<with>

  • @MuratKarakuş:"在我的机器上工作"并不意味着它是正确的.在相等上返回"true"显然违反了[比较函数的要求](http://en.cppreference.com/w/cpp/concept/Compare). (3认同)