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

Dec 19, 2013 at 6:20pm
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
Dec 19, 2013 at 6:24pm
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.
Dec 19, 2013 at 6:30pm
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
Dec 19, 2013 at 6:32pm
There is a ready made function for this?

In other language i can do something like if (myVector(3) is not null) ....
Dec 19, 2013 at 6:36pm
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.
Dec 19, 2013 at 6:54pm
In other language

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