How can I write a piece of code that throws an error as soon as it gets out of range and prints something on screen? If I don't write any code and some part of the vector that doesn't actually exist gets mistakenly accessed, I get some sort of warning complaining about the range but I don't know what vector! also.. the program crashes and that's not good.
Use vector.at() function to access vector indexes. Its has exception handling that will throw "out of range" if you try to access inaccessible data.
1 2 3 4 5 6 7
vector<int> vec.
vec.push_back(4);
vec.push_back(3);
cout<<vec.at(0); //4
cout<<vec.at(1); //3
cout<<vec.at(2); //program stops and throws out of range exeption.