Checking if any particular element exists or not in the C ++ STL vector

I wanted to check if an element exists in a specific vector location, say i, before accessing it like v [i]. Could you tell me how can I do this?

Thanks.

+3
source share
5 answers
if (0 <= i  &&  i < v.size()) {
  // OK
  std::cout << v[i]; // Example
} else {
  // Wrong
}
+9
source

An element is guaranteed to exist in every position i, where i >= 0and i < v.size(), since vectors are adjacent sequences of elements and β€œholes”, it is impossible.

+4
source

v.size().

+2

, , , , .

, , . std:: map, , - .

, , .

+1

I understand that you have std::vectorprealocated in a specific dimension, say n, and you want to find out if an element in index i( i < n) was initialized or just highlighted .

Like @Thomas Matthews, you can use a second data structure, a simple bool[n]one in which kyou store in the index trueif the element with the index kin yours vectorexists falseotherwise.

      0 1 2 3 4 5
v = [ *   *   * * ]

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

Source: https://habr.com/ru/post/1725647/


All Articles