Search code examples
c++stdvector

Vector going out of bounds without giving error


I have a std::vector. I check its size which is 6 but when I try to access vec[6] to check whether it will give error, I get no error but some number instead. Should not it give an error?

edit: something like:

struct Element
{
    std::vector<double> face;
};

int main()
{
    Element elm;

    .... // insert 6 elements into elm.face

    std::cout << elm.face.size() << std::endl; // answer is 6
    std::cout << elm.face[6] << std::endl; // answer is some number
}

Solution

  • std::vector performs bounds checking when the at() member function is used, but it does not perform any checks with operator[].

    When out of bounds operator[] produces undefined results.