以下代码用于打印整数列表中的最大数字。我得到:
*** 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是整数的向量。
编辑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函数违反了严格的弱排序规则。排序要求比较函数应满足严格的弱排序规则。如果这个承诺被打破了,那么std::sort正确行为的承诺也是如此。事实上,当我在MSVC(VS2015)下编译它时,我得到了一个断言失败,即比较函数不满足排序条件。例如这条线:
if(a == b)
return true;
显然违反了条件。查看此帖子了解更多见解。
顺便说一句,如果你只想按字典顺序对整数进行排序,你可以只做
bool comp(int a,int b)
{
return to_string(a) < to_string(b);
}
如果你想要"先大数字"的等价物,只需交换<带有>
我使用了您的comp
函数,并创建了一个示例案例研究来检查错误。然而,对于array of zeros
的情况,我没有得到任何错误。请检查示例程序。
错误
然而,下面的场景会导致运行时错误。
// Pay attention: Array stores numbers in descending order.
// If we stored in ascending order, there won't be a problem.
for(int i=20; i>0; ++i)
v.push_back(i);
我希望这将有助于找到解决方案。
示例程序
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>
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] > b1[l1-1])
return false;
else
return true;
else
if(a1[l2] > a1[l2-1])
return true;
else
return false;
}
int main(int argc, const char *argv[])
{
vector<int> v;
for(int i=0; i<20; ++i)
v.push_back(0);
sort(v.begin(), v.end(), comp);
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
return 0;
}