Element testing in array

Hello everyone !
I am having a problem where I have a vector and in some cases this vector is going to be checked in some positions that an element doesn't exist.
So for example vector[-1] is an exception.

How can I do something like if( myVector[i] == null ) ... or undefined ?
I checked the internet and all were saying use the find method or use a different data structure like map etc etc ... I just want to test if element exist not find the element.
closed account (10oTURfi)
if(i>myVector.size()-1) cout << "this is bad";
Last edited on
better:
if (i < 0 || i >= myVector.size()) cout << "this is bad";

If i is of an unsigned type or sizeof(myVector.size()) >= sizeof(i) you don't have to test if i is less than zero:
if (i >= myVector.size()) cout << "this is bad";
Last edited on
Every element in a vector is defined.

Use the at() member function to have checked access to elements:

1
2
try { cout << myvec.at( -14 ) << endl; }
catch (...) { cout << "fooey!\n"; }

Hope this helps.
Last edited on
Topic archived. No new replies allowed.