开发者

Problem with iterators

Basically I wrote some code to print out a triangle recursively - and originally I used an iterator in the code to take the inner parts of a triangle and include them in the complete 'picture'.

Anyway here's the code:

#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 开发者_如何学Goprogram, 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;
}

This code doesn't work however if you replace the iterator with the following section of code it works fine.

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

My question is why doesn't iterators work in this context.


I know what it is. I must have used iter++ in the original code. It works in both compilers. It's a mistake I've made before.


Maybe try

#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;
}

No recursion, less memory consumption, faster. And won't fall into infinite loop if max_stars < 1. And no iterators :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜