ebaccount
ebaccount

Reputation:

checking whether a particular element exists or not in a c++ STL vector

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.

Upvotes: 3

Views: 6147

Answers (5)

Iulius Curt
Iulius Curt

Reputation: 5114

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 ]

Upvotes: 0

Alexey Malistov
Alexey Malistov

Reputation: 27023

if (0 <= i  &&  i < v.size()) {
  // OK
  std::cout << v[i]; // Example
} else {
  // Wrong
}

Upvotes: 9

CB Bailey
CB Bailey

Reputation: 793359

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.

Upvotes: 4

Thomas Matthews
Thomas Matthews

Reputation: 57749

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.

Upvotes: 1

Parappa
Parappa

Reputation: 7676

Use v.size().

Upvotes: 2

Related Questions