3

I wanted to check whether an element exist at a particular vector location, say i, before accessing it like v[i]. Could you let me know how can I do that?

Thank you.

2
  • 1
    I'm very confused. You have to access the vector in order to find out if an element exists. So how do you determine if an element exists at position i without accessing the vector? Use another vector? Commented Dec 14, 2009 at 20:55
  • Accessing the vector is obviously OK, but calling operator[] with unchecked arguments ("like v[i]") isn't. Commented Dec 15, 2009 at 11:05

5 Answers 5

9
if (0 <= i && i < v.size()) { // OK std::cout << v[i]; // Example } else { // Wrong } 
Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand how the size of a vector can be used to find out if an element in the vector exists? Given a vector of 500 elements, how does the size method help me determine if element at position 10 exists?
I think the question means "how to find if there is an element (or any value) at the position indexed by i"
@Thomas, size() returns the number of elements actually in the vector. so v[n] where 0 <= n < size() must contain an element.
4

An element is guaranteed to exist at every position i where i >= 0 and i < v.size() as vectors are contiguous sequences of elements and "holes" are not possible.

Comments

2

Use v.size().

1 Comment

I know how, but I guess that your answer won't help the questioner. Use how?
1

If you want to know if an element exists in a vector, the quickest method is to sort the array then use a search method such as binary search.

If this action is performed many times, perhaps changing the data structure will yield better performance. An std::map is good for this, and if your compiler has one, use a hash table or map.

Otherwise the only way to determine if a value exists in an vector without accessing the vector is to use a second data structure to remember the value and position.

1 Comment

This may or may not be quicker. A linear search may well be much quicker than sorting if the search is only performed once per sort.
0

I understand you have a std::vector preallocated at a specific dimension, let's say n, and you want to see if the element at index i (i < n) was initialized or is just allocated.

Like @Thomas Matthews said, you can use a second data structure, a simple bool[n], in which, at index k, you store true if the element at index k in your vector exists and false otherwise.

 0 1 2 3 4 5 v = [ * * * * ] 0 1 2 3 4 5 exists = [ true, false, true, false, true, true ] 

Comments