C ++ check if element exists in vector

I am working with a vector and have to check if an element exists at a specific location in the vector, like myvec[7]

I need to work outside of the loop and be able to do this check for any given point in the vector. What would be the most efficient way to do this with a vector?

+3


source to share


2 answers


This is a test that you are looking for: (myvec.size() >= 8)

. In C ++, there are no empty elements in the vector, i.e. Vector elements have consecutive indexes.



+7


source


There are two ways to do this.

The following code examples assume that we want to do something with v [n] in v.

Method 1:

if(n<v.size()) 
    //do something with v[n]
else
    //do something else

      



Method 2:

//do something using v.at(n) instead of v[n]

      

This will throw an exception if you try to access an element that is not in the vector.

Which one to use? Depends on the case. Can you work if the element is missing from the vector? Use the first method.
Having this element is critical to your code. Use the second method, let the STL check for its presence for you, and don't forget to catch the exception.

+2


source







All Articles