今天做leetcode中的Largest Number,程序所出的异常,简直让我抓狂,是我程序的bug,还是stl sort的bug啊,不知道有什么好方法,可以确定程序中的问题。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
#include<iterator>
using namespace std;
static int i=0;
bool compare2(const int t1,const int t2){
try{
i++;
if(0!=t1||0!=t2) cout << "i=" << i << ";" << "t1=" << t1 << ";"<< "t2="<<t2<<endl;
stringstream s;
s<<t1;
string s1=s.str();
s.str("");
s.clear();
s<<t2;
string s2=s.str();
bool exchange=false;
int n,m;
if(s1.size()>=s2.size()){
n=s1.size();
m=s2.size();
}
else{
n=s2.size();
m=s1.size();
string t=s1;s1=s2;s2=t;
exchange=true;
}
int i=0,j=0;
while(i<n){
if(s1[i]>s2[j])return exchange?false:true;
else if(s1[i]<s2[j]) return exchange?true:false;
i++;
j=(j+1)%m;
}
}
catch(...){
cout << "an exception was thrown" << endl;
}
return true;
}
string largestNumber(vector<int> &num){
try{
ostream_iterator<int>output(cout," ");
copy(num.begin(),num.end(),output);
cout << endl;
sort(num.begin(),num.end(),compare2);
//ostream_iterator<int>output(cout," ");
copy(num.begin(),num.end(),output);
cout << endl;
stringstream ss;
for(int i=0;i<num.size();i++){
ss << num[i];
}
return ss.str();
}
catch(...){
cout << "异常"<<endl;
}
}
int main(){
int A[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
vector<int>num(A,A+sizeof(A)/sizeof(A[0]));
cout << largestNumber(num) << endl;
return 0;
}
使用这么多0进行运行测试,leetcode判定为运行时错误,本机上程序运行的结果,很奇葩!!
运行前num的值全是0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
i=133;t1=537;t2=0
i=134;t1=-1218341808;t2=0
i=265;t1=0;t2=529
i=267;t1=0;t2=537
i=268;t1=0;t2=537
i=399;t1=537;t2=0
i=400;t1=-1218341808;t2=0
i=401;t1=0;t2=537
i=403;t1=0;t2=537
i=404;t1=0;t2=537
i=535;t1=537;t2=0
i=536;t1=-1218341808;t2=0
......
......
i=10878;t1=0;t2=537
i=10999;t1=0;t2=537
i=11121;t1=0;t2=537
i=11244;t1=0;t2=537
i=11368;t1=0;t2=537
i=11493;t1=0;t2=537
i=11619;t1=0;t2=537
i=11746;t1=0;t2=537
i=11874;t1=0;t2=537
i=12003;t1=0;t2=537
运行之后num的值变了,如下:
537 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
53700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000
这个纳闷的537是怎么出来的呢?
尝试使用程序中的异常处理来捕捉异常,结果并没有捕捉到异常,这是什么问题呢?Mark亟待解决!!!