Search code examples
c++vectorsizecapacity

Access the element out of size in C++ vector


Today I try something like this in VS2012 and Max OS 10.7

    vector<int> vec;
    vector<int> vec2;
    for(int i = 0;i < 100 ;i++){
        vec.push_back(i);
    }

    cout << "size: " << vec.size() << endl;
    cout << "capacity: " << vec.capacity() << endl;
    cout << vec[127] << endl;
    //vec2.reserve(10);
    fill_n(vec.begin(),128,-1);
    cout << vec[127] << endl;
    return 0;

as we know the size of vector is the real number of elements in the container, the code above can cause runtime error in VS2012, but it works fine on Max OS, and I try it in Ideone.com and also run successfully, I am not sure if something wrong with the definition of size and capacity, why I can access element out of size?

PS: the capacity at this situation on my computer is 141 on VS2012 and 128 on Mac OS and Ideone.com


Solution

  • std::vector operator [] won't throw any out of range error. It's a undefined behaviour to access element greater than the vector size using [] operator.

    Use std::vector::at instead, which throws std::out_of_range