3

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?

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Boris. I'm new in c++. You are saying that something like: std::vector<int> test; test.push_back(0); test[2] = 2; std::cout << test[0] << ", " << test[2]; Is not possible? I thought that it was possible to have a "blank" element on a vector, like in the example I just mentioned. How can we identify those blank elements?
@EduardoMaia definitely not possible. This is not Ruby or Python. This will throw an exception in C++
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.