Using push_back vs at in a vector in C++

The issue in this loop:

for (unsigned i=0; i<myvector.size(); i++)
{
    myvector.push_back("hi");  //Note: using push_back here.
}

is that if you ever enter the loop, i.e. myvector is not initially empty, then each push_back will increase the size of the vector. Since i is incremented once each time in the loop, it will never catch up to the size of the vector, and you end up with an infinite loop.


.at() doesn’t have this problem, since it only indexes into the vector, without ever changing its size. So long as the argument to at is a valid index, you can access this position without any issues.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top