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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With