std :: vector :: at already does this. That way you can use the at method instead of operator [] . It rejects std::out_of_range for an invalid index.
Please note that you will need to do significant work to achieve std::vector performance. But still, if you want to stick to your container and want to get out of [] , then the at std::out_of_range method is the best choice among the standard exception classes. Otherwise, you need to define your own custom exception class.
source share