今天做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亟待解決!!!