declaring variables in a while loop question

I am in a situation where I need to create a new instance of a vector at every iteration of a loop. I don't want to declare it outside the loop and "clear" it every time because I think that reduces usability of the code. So I've done something like this:

1
2
3
4
5
6
while (condition)
{
  std::vector<type> myvec;
  
  myvec.push_back(somenumber);
}


My assumption is that myvec will never contain more than 1 number, is that right? Every time std::vector<type> myvec; runs the vector will be essentially reset to 0 size, right? If so, how do you know this?
You are correct in your assumption. myvec will essentially go out of scope at the end of each iteration of the loop.

If you don't want to declare it outside of the loop, you could make it static so it won't be destroyed when it goes out of scope.

You could also add more braces outside of the loop to manually make it go out of scope.
1
2
3
4
5
6
7
{
    std::vector<type> myvec;
    while(condition)
    {
        myvec.push_back(somenumber);
    }
}
Last edited on
Topic archived. No new replies allowed.