How to check if a specific vector[n] exist?

Hello,

there's a way to check if a specific index of a vector exist without getting error or program crash?

I would like to knoe if there is something similar to this:

if (myVector.at(3) is not null or not empy)
cout << myVector.at(3) << endl;

thank you
Look at what myVector.size() returns.

If your index is strictly lower than size() (don't forget the index starts at 0), then there is guaranteed to be an item there.
closed account (Dy7SLyTq)
there are two other options. if you have a vector with 5 elements and try to access element 10, it will throw an exception. you can catch it and say something like out of bounds. otherwise you could make a class that inherits from vector that checks if the number passed to at is in bounds. if not, do nothing
There is a ready made function for this?

In other language i can do something like if (myVector(3) is not null) ....
If you are just trying to determine whether or not the element exists, just do a bounds check:
if (index > 0 && index < myVector.size()).

If you have a vector of pointers, they are not always guaranteed to be initialized to NULL, so you have to make sure that when you create your vector and/or expand it that they are explicitly initialized that way.
Then,
if (myVector[index] != NULL)

Technically, you could get away with:
if ((index > 0 && index < myVector.size()) && (myVector[index] != NULL)).

This works for vectors of pointers. If you have vectors of references or values then you don't really have a NULL condition and you have to detect that the value is in an 'empty' state.
In other language

Well this not other languages.
Topic archived. No new replies allowed.