2010-02-19 63 views
0

基本上我寫了一段代碼遞歸地打印出一個三角形 - 和原本我用一個迭代中的代碼採取三角形的內部部件和將它們包括在完整的「圖像」。問題的迭代器

反正這裏的代碼:

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 


vector<string> print_triangle(int max_stars) 
{ 
vector<string> buffer; 

if(max_stars == 1) 
{ 
    buffer.push_back("*"); 
    buffer.push_back("*"); 
    return buffer; 
} 

//This is the first part of the program that writes the first line of 
//asterisks 
string tmp; 
for(int i = 0; i < max_stars; i++) 
{ 
    tmp.push_back('*'); 
} 

buffer.push_back(tmp); 

//This is the recursive part of the program, which generates the 
//remainder of the triangle pattern - the inner part. 
vector<string> inner_part; 
inner_part = print_triangle(max_stars - 1); 

vector<string>::iterator iter = inner_part.begin(); 
      for(; iter != inner_part.end(); ++iter) 
      { 
       buffer.push_back(*iter); 
      } 
string tmp1; 
for(int i = 0; i < max_stars; i++) 
{ 
    tmp1.push_back('*'); 
} 
buffer.push_back(tmp1); 

return buffer; 
} 

,如果你用下面的一段代碼,它工作正常更換迭代這個代碼不工作,但是。

for(int i = 0; i < inner_part.size(); ++i) 
{ 
    buffer.push_back(inner_part[i]); 
} 

我的問題是爲什麼不在這種情況下工作的迭代器。

+2

沒有迭代器你可能會得到更快的答案如果你給比「這個代碼不工作」更多細節。何時:編譯時間?運行?怎麼了? – 2010-02-19 13:54:57

+0

一個非常簡單的問題... – user231967 2010-02-19 13:56:03

+1

BTW一個完全複雜的解決方案:'的std :: string(MAX_STARS,「*」)'將創建一個字符串,你想要的方式。你可以將它保存在一個'stars'變量中,然後在遞歸之前和之後將它放到'buffer'中,所以你不必構建它兩次。 – 2010-02-19 13:57:45

回答

0

我知道它是什麼。我必須在原始代碼中使用it ++。它適用於兩種編譯器。這是我以前犯的一個錯誤。

+2

它應該與'++ iter'或'iter ++'一起使用。如果這有所作爲,那麼在某個地方會發生一些有趣的事情。 – 2010-02-19 14:27:29

+0

讓我在我的原始編譯器中嘗試它,並確認我仍然得到相同的錯誤。 – hairyyak 2010-02-19 14:38:30

+0

不管它現在在工作 - 不管我做什麼。我完全困惑。 – hairyyak 2010-02-19 14:40:13

0

也許嘗試

#include <string> 
#include <vector> 

using namespace std; 

vector<string> print_triangle(int max_stars) 
{ 
vector<string> buffer; 
if (max_stars < 1) 
    return buffer; 

buffer.reserve(max_stars + 2); 

while (max_stars > 1) 
{ 
    buffer.push_back(string(max_stars, '*')); 
    max_stars--; 
} 
buffer.push_back("*"); 
buffer.push_back("*"); 

return buffer; 
} 

沒有遞歸,內存消耗少,速度更快。而不會陷入無限循環,如果MAX_STARS < 1和:-)

+0

最初的問題表明它必須遞歸地完成,但你不知道除了我喜歡迭代器。 – hairyyak 2010-02-19 14:42:07

+0

但是,感謝您編寫了一種替代方法。 – hairyyak 2010-02-19 14:46:24