Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing a vector in C++

Tags:

c++

I have a vector declared as a global variable that I need to be able to reuse. For example, I am reading multiple files of data, parsing the data to create objects that are then stored in a vector.

vector<Object> objVector(100);

void main()
{
 while(THERE_ARE_MORE_FILES_TO_READ)
 {
    // Pseudocode
     ReadFile();
     ParseFileIntoVector();
     ProcessObjectsInVector();
     /* Here I want to 'reset' the vector to 100 empty objects again */

 }

}

Can I reset the vector to be "vector objVector(100)" since it was initially allocated on the stack? If I do "objVector.clear()", it removes all 100 objects and I would have a vector with a size of 0. I need it to be a size of 100 at the start of every loop.

like image 443
Blade3 Avatar asked Mar 11 '10 16:03

Blade3


1 Answers

I have a vector declared as a global variable that I need to be able to reuse.

Why? It’s not clear from your code why the variable must be global. Why can’t you declare it inside the loop? Then you don’t need to reset it, this will be done automatically in each loop.

In order to access the variable from the other methods, pass it in as a parameter (by reference, so you can modify it). Having a global variable is rarely a good solution.

Something else: main must never have return type void, this is invalid C++ and many compilers will reject it.

like image 54
Konrad Rudolph Avatar answered Sep 19 '22 15:09

Konrad Rudolph