C ++ check if element exists in vector
2 answers
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 to share