I am a newbie to c++ STL vectors so sorry for silly questions in advence. :) In my program, I have a vector which needs to store unknown number of elements. Do I have to check if the vector has achieved its max_size bef开发者_如何学Pythonore adding an new element to it ? Will a c++ compiler throw an exception automatically when a program tries to add elements to a full vector ?
Thank you very much, Cassie
If the std::vector
has reached its max size, attempting to insert another element will result in the underlying allocator throwing a std::bad_alloc
exception.
Note, however, that the maximum size for a vector is typically very, very large (e.g., the maximum value that can be represented by size_t
divided by the size of the element type), so it is unlikely, if not impossible, for you to reach the maximum size before you run out of contiguous memory in which the vector can be stored.
Since you didn't include any example code, just to be clear it depends on how you do the adding. If you are using push_back()
, then yes, the vector will automatically expand. If you are ding something like v[count++]=value;
, then you could run into a problem, as this does not check that the index is in range.
No. Inserting an element just can invalidate any iterators, references, or pointers to elements in the vector
. Your insertion will (nearly) always succeed.
I say "nearly" because an exception could occur either if there's not enough memory to move the underlying array (because it's reached max_size
-- typically in the millions or billions), or if an exception occurs constructing the new element. In these cases, a c++ exception is thrown.
No, you don't have to worry. Vectors, and other STL containers automatically grow as needed (unlike ordinary arrays).
精彩评论