tags:

views:

100

answers:

4

Hi dear all,

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 before 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

+1  A: 

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.

rlbond
+7  A: 

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.

James McNellis
… which is to say, you get a `bad_alloc` before that point, or (more likely on a desktop OS) unexpectedly and unceremoniously terminate.
Potatoswatter
-1 This doesn't respond to the answer.
Vicente Botet Escriba
A: 

No, you don't have to worry. Vectors, and other STL containers automatically grow as needed (unlike ordinary arrays).

mathmike
+4  A: 

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.

KeithB
+1 Assign an element using the operator[] is unchecked for performances reasons.
Vicente Botet Escriba