You're making what is called a circular buffer.
Consider the simple example of a
double*
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
// needed variables
double *begin;
double *current;
double *end;
//Psuedo-Code
void create(const unsigned int size)
{
begin = new int[size];
current = begin;
end = begin + (size - 1);
}
void add(double newDouble)
{
*current = newDouble;
// Here make it circular
if (current == end) current = begin;
else current++;
}
void print(void)
{
double *iterator = current;
do
{
std::cout << *iterator << '\n';
if (iterator == end) iterator = begin;
else iterator++;
}
while (iterator != current);
}
|
Thats basically how it goes. You of course have to
delete
begin at some point, and take care of your pointers in general (set them to NULL when not in use). If you wanted to have something like
char**
, then this is even more critical. At that point, your add looks a little different, you have to delete then allocate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
char** begin;
char** current;
char** end;
void add(char* newString)
{
if (*current) // we set every char* in the buffer to NULL upon construction
// so this means there is a c-string here
{
delete [] *current;
}
*current = new char[strlen(String) + 1];
strcpy(*current, String);
if (current == end) current = begin;
else current++;
}
|
If you're going all out with your iterator (has it's own class), then overload the ++ -- operators properly.
I did this for my C homework a while back (though wrote it in C++ first).
http://www.cplusplus.com/forum/beginner/74456/
That theoretically works if you set up main() with an ifstream to read from.
Edit: Oh yeah, and your print needs to know if the entire buffer has been used, or if current points to NULL. Why setting these things to NULL is important.