Let’s have a function func which allocates memory for vec. Also let’s func is called many times in a loop.
void func ()
{
std::vector<int> vec;
vec.resize(someNumber);
}
for (int i=0; i<someNumber; ++i)
{
func ();
}
How I can allocate memory for vec only once in a loop?
As Beta said, every time the function
func()is called a new vector is created and is destroyed when the function exits. If you want to have a single vector which gets resized which each call, you may want to do something likeor you can direcly initialise your vector with the max memory you will need as