Search code examples
c++vectorsize

Why are vectors' size static and we still can add more values?


I'm a complete beginner to C++ but I have some basics knowledge in programming (Python mainly) and I'm trying to learn C++. As the question implies, vectors have static sizes (at least what I've read in my learning material) but we still can add more values to what the size authorize. I wrote a simple code to know what error I get if I pass more values to a vector than the limit authorized by it's size and surprisingly I didn't get any error.

The code are these simple lines:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int it=0,a;
    vector<int> v(10); 
    for(a=1; a<21; a++)
    {
            v[it]=x;
            cout << v[it] << endl;
            it++;
    }
    cout<<"Values stored in v";
    for(i=0;i<it;i++)
        cout<<v[i]<<" ";
    cout<<endl;
    cout<<"Vector's size : "<<v.size()<<endl;
    return 0;
}

What I get with cout<<"Values stored in v"; are all values from 1 to 20, but I still get that the size is 10.

If that can helps I'm on Windows 10 x64 and using Qt Creator compiler.


Solution

  • What is fixed is

    sizeof( vector<int> )
    

    A vector can contain varying number of elements, but that elements are stored on the heap, hence do not contribute to the vectors sizeof. The number of elements is v.size() (and that can change).

    You create a vector with 10 elements:

    vector<int> v(10); 
    

    But then you attempt to access elements that do not exist in the loop. For example v[10] will not cause a compiler error, it is also not guaranteed to cause a runtime error. Nevertheless, it is guaranteed wrong. Accessing the vector out of bounds causes undefined behavior. The output of the code could be anything.