Reputation: 4016
I'm working with a vector and need to check if there exists an element at a specific spot in the vector, like myvec[7]
I need to work outside of a loop and be able to perform this check for any given point in the vector. What would be the most efficient way to do this with a vector?
Upvotes: 3
Views: 9820
Reputation: 1419
There are two ways of doing this.
Next code examples will assume we want to do something with element v[n] in vector v.
Way 1:
if(n<v.size())
//do something with v[n]
else
//do something else
Way 2:
//do something using v.at(n) instead of v[n]
This will raise an exception if you try to access element that isn't in vector.
Which one to use? Depends on the case.
Can you work if element isn't in the vector? Use first method.
Having this element is crucial for your code. Use second method, let STL check its presence for you and don't forget to catch an exception.
Upvotes: 3
Reputation: 46943
This is the check you are looking for: (myvec.size() >= 8)
. In C++ there are no blank elements in a vector - i.e. the vector elements are with consecutive indices.
Upvotes: 8