2012-03-02 66 views
1

我快到這裏 http://www.spoj.pl/problems/HELLOKIT/C++程序,以優化

顯然上市這一問題進行審查,這是不被接受。我想知道我應該如何優化下面的代碼。邏輯很簡單,但我想知道爲什麼我總是爲簡單的問題編寫這樣長的程序。非常感謝。我希望你能幫助我寫出優秀和強大的程序。 下面是代碼

#include<iostream> 
#include<stdio.h> 
#include<string.h> 
#include<conio.h> 


using namespace std; 

void rotate(string a , int b){ 

string newstring; 
bool result=true; 
char displaystr[50],displaystr2[50],sourcestring[50]; 

    for(int i=0;i<b;i++){ 
    newstring = newstring.append(a);//Append the string with itself b times 
    } 
    cout<<newstring<<endl; 
    int length = newstring.length() ; 
for(int l=0;l<length;l++){ 
     sourcestring[l]=newstring[l]; //copy the string to a char* 
    } 
    int index=0,counter=1;//counter keeps track of changing source string 
    while(result){ 
    index=0; 
    while(index<length-1){ 
    if(counter==1){ 
        displaystr[index] = sourcestring[index+1];//rotating the string 
        displaystr[length-1] = sourcestring[0]; 
        index++; 
    } 
    else{ 
        displaystr2[index] = displaystr[index+1];//rotatinsg when source change 
        displaystr2[length-1] = displaystr[0]; 
        index++; 
    } 
    } 
if(counter>1){ 
     for(int i=0;i<length;i++) 
     displaystr[i]=displaystr2[i]; 
} 
counter++; 
if(strncmp(displaystr,sourcestring,length)==0){ 
result=false; 
return; 
} 
for(int i=0;i<length;i++) 
cout<<displaystr[i]; 
cout<<endl; 
} 
int main(){ 

int testcases=0; 
string key; 
int num=0; 
string keyarr[10]; 
int numarr[10]; 
int i=0,j=0; 
while(testcases<10){ 
getline(cin,key); 
if(key==".") 
break; 
cin>>num; 
    cin.ignore(1024, '\n'); 

keyarr[i]=key; 
numarr[i]=num; 
i++; 
testcases++; 

} 

for(int j=0;j<i;j++){ 

    rotate(keyarr[j],numarr[j]); 
    } 
getch(); 
return 0; 

} 

的代碼示例IAM談論的是這個

#include<iostream> 
#include<stdio.h> 
#include<string> 
#include<conio.h> 


using namespace std; 

void rotate(string a , int b){ 
string newstring,displaystr; 
for(int i=0;i<b;i++){ 
    newstring = newstring.append(a); 
    } 

    int length = newstring.length() ; 
    int index=0; 

while(index<length-1){ 

        displaystr[index] = newstring[index+1]; 
        index++; 

    } 
     displaystr[length-1]=newstring[0]; 
     cout<<displaystr; 


} 

int main(){ 
rotate("love",2); 
getch();  
return 0; 
} 
+0

我注意到一些事情:我希望相關代碼不超過十行(最大!)和輸入例程數量。你的代碼爲什麼這麼長?另外,爲什麼你使用固定大小的緩衝區?我沒有更進一步說實話。 – 2012-03-02 13:39:45

+5

我認爲這屬於codereviews。 – 2012-03-02 13:40:00

+0

請更好地格式化您的代碼。 – m0skit0 2012-03-02 13:44:30

回答

1

的懸而未決的問題,我可以在手看(無論是任務的多少行裏應該或不應該採取實現)是你在編寫代碼時需要使用縮進。如果雜亂無章 - 編寫複雜的代碼很容易 - 縮進有助於保持它的組織性和重要性,可讀性。如果你這樣做,你的代碼會變得更高效,你會感到驚訝。

說了這些之後,編程就像任何其他技能一樣。你需要不斷練習,你需要學習,保持你的技能最新。通過教程,書籍和其他程序員等學習新概念。接受挑戰並嘗試針對單個問題考慮不同(創造性)的方法 - 這尤其可以幫助找到有效的方法來完成任務。通過工作,您可能會發現自己正在編寫效率更高的代碼。練習,練習,練習,並從錯誤中吸取教訓。

+0

良好的提示,特別是因爲代碼實際上錯過了大括號。 – 2012-03-02 13:49:01

+0

謝謝Alex的建議。 Iam在處理字符串時也有一些問題。之前,當我沒有使用固定大小的緩衝區時,我使用了字符串。但是當我運行它們時,它們顯示錯誤的ptr錯誤。你有什麼話要說嗎? – YuNo 2012-03-02 13:50:46

+0

嗨康拉德,我看到並修復它。 – YuNo 2012-03-02 13:51:55