tags:

views:

116

answers:

2

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

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.

A: 

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.

hairyyak
It should work with either `++iter` or `iter++`. If that made a difference then there's something funny going on somewhere.
Peter Alexander
Let me try it in my original compiler and confirm I still get the same error.
hairyyak
Nope it's working now - regardless of what I do. I'm totally confused.
hairyyak
A: 

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 :-)

Tadeusz Kopec
The original problem stated that it had to be done recursively but you didn't know that besides I like iterators.
hairyyak
But thanks for writing an alternative method.
hairyyak