I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.
The general rule is that, if you don't already know the size of the
array, you cannot determine the size of the array. The rule works as
follows:
std::vector (the standard C++ resizeable array) and boost::array (a
third-party fixed-size array class, available from boost.org) both
know their own size and can supply it on request:
#include <vector>
template <typename T>
std::size_t size (const std::vector<T> &v) { return v.size(); }
#include <boost/array.hpp>
template <typename T, std::size_t N>
std::size_t size (const boost::array<T, N> &v) { return v.size(); }
A named array also knows its own size, but a function can only
determine that size if the array is passed by reference:
template <typename T, std::size_t N>
std::size_t size (T (&v) [N]) { return N; }
template <typename T, std::size_t N>
std::size_t size (const T (&v) [N]) { return N; }
Besides that (or the rare pointer-to-array), arrays are passed by
pointer to the first element, never by value. That means that the
following prototypes are identical:
void f (int *array);
void g (int array[]);
void h (int array[20]);
(Note that all three functions accept any array of ints, be it int[50]
or int[5]. The "20" is misleading, allowed but ignored by C++. Don't
put it in your code.)
Since a pointer does not maintain the size of the array into which it
points (if it points into one at all), you must pass that in yourself:
template <typename T> void f (const T *v, std::size_t n);
int main () {
int array[20];
f(array, size(array)); // use the by-reference size() function
}
Also, since pointers do not maintain sizes, it is impossible to
calculate the size of an array allocated with new[] or similar. The
solution is to use std::vector instead, or to maintain the size
yourself. (I go with std::vector in almost all cases.)
I used to think I could just do: if (arr) ...
However, if this element's value happens to be 0, the conditional
will return false, even though the element actually exists.
All elements of an array exist.
Any ideas? Can you check if the element == null?
Not unless that element is a pointer. But that's not what you meant.
- Shane