Very simple: Find out if element of array exists

  • Thread starter Noah Spitzer-Williams
  • Start date
N

Noah Spitzer-Williams

Hello guys,

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

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.

Any ideas? Can you check if the element == null?

- Noah
 
K

Kevin Goodsell

Noah said:
Hello guys,

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

You can't pass arrays to functions.

All elements in an array exist.

I don't understand the question.

-Kevin
 
A

Alf P. Steinbach

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

That is very simple indeed: all elements of an array exist.
 
G

Gary Labowitz

Noah Spitzer-Williams said:
Hello guys,

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

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.

Any ideas? Can you check if the element == null?

If you set up an array of points to your elements (even if they were
elements of an array) then you can have the pointer as NULL when you have no
valid value for that element. But any array you declare will have elements
with some value in each of them.
 
S

Siana

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

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.


First of all, when array names are used as the argument to a function,
it is the address of the first element (ie. a pointer) that is
actually passed. This means you usually also have to pass in the size
of the array. ((A better choice would be a vector!))

Anyway, when you create an array, say of size 10, all ten elements
"exist". If you want to have 'gaps' in the array (that is, an array of
size 10 where not all of the elements have useful data), you probably
need to create an array (or vector) of *pointers to data* rather than
an array of data. That way, you can initialize all elements to 0
(null) and be able to check for real data at any location.

Of course, you are now getting into the realm of dynamic allocation
with new and of course having to clean up that memory with delete.

If this is what you're looking for and still need some help, reply to
this thread for more details (since I don't know how much of this you
know how to do).

S.

PS. Shame some of the other posters just give you a smart alec answer.
Not everyone here is like that.
 
S

SaltPeter

Noah Spitzer-Williams said:
Hello guys,

I would like to do something seemingly simple: find out if an
element in an array that is passed to my function exists.

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.

Any ideas? Can you check if the element == null?


When your garbage can array holds garbage , it's still an array of garbage
cans.
What's more disconcerting is the fact that garbage is initialized
differently depending on the compiler used. And the pile of garbage in each
can is never NULL, it's just garbage and it should be treated as such..
 
N

Noah Spitzer-Williams

What I mean is that, say the array that is passed has 20 elements...
how do I figure this out?

If I do array[50] on a 20 element array, obviously c++ will error. I
need to figure out the size of this array.

- Noah
 
A

Attila Feher

Noah said:
What I mean is that, say the array that is passed has 20 elements...
how do I figure this out?

If I do array[50] on a 20 element array, obviously c++ will error. I
need to figure out the size of this array.

You cannot. You have to pass it to the function as a separate argument.
 
K

Kevin Goodsell

Noah Spitzer-Williams wrote:

Please don't top-post.

http://www.parashift.com/c++-faq-lite/how-to-post.html#faq-5.4
What I mean is that, say the array that is passed has 20 elements...
how do I figure this out?

Pass the size in separately. You can't create information that isn't
there - somehow you have to get the size information into the function.
If I do array[50] on a 20 element array, obviously c++ will error.

That's not obvious at all. Indexing beyond the end of an array gives
undefined behavior. Anything can happen - an error, no error, random
file deletion - anything.
I
need to figure out the size of this array.

The size of an array is easy to figure out:

size_t nelements = sizeof(array) / sizeof(*array);

HOWEVER this only works with *arrays*, NOT with pointers. In particular,
you cannot do this:

int *array = new int[somesize];
// ...
size_t nelements = sizeof(array) / sizeof(*array); // WRONG!!

Or this:

void somefunc(int array[])
{
size_t nelements = sizeof(array) / sizeof(*array); // WRONG!!
// ...
}

Since in these cases, the thing called 'array' is actually a *pointer*,
not an array.

-Kevin
 
D

Dietmar Kuehl

Attila Feher said:
You cannot. You have to pass it to the function as a separate argument.

If he spelled the array declaration correctly, he could use the 'size()'
member function, for example:

void f(std::vector<int>& array) {
std::cout << "size: " << array.size() << "\n";
// ...
}

Of course, this assumes that he is not fiddling around with things only
few people need to touch, ie. built-in array.

There are a few situations, where built-in array come in handy, though,
namely when defining a set of elements, eg.:

std::string weekdays[] = {
"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
};

Of course, in this situation we know how many elements the array has but
in general we don't. In these cases, the size of the array can be
determined using a simple template function:

template <typename T, int sz> int size(T (&)[sz]) { return sz; }

int main() {
std::string weekdays[] = { ... };
std::cout << "no. weekdays: " << size(weekdays) << "\n";
}

This is about the only situation where I would suspect a user really
relying on use of a built-in array. In other situations, appropriate
classes like eg. 'std::vector<T>' are much preferable.
 
S

Shane Beasley

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
 
W

WW

Dietmar said:
If he spelled the array declaration correctly, he could use the
'size()' member function, for example:

void f(std::vector<int>& array) {

Hehe. Hehehehe. :) Spelled. :)
 
R

Ron Natalie

Noah Spitzer-Williams said:
If I do array[50] on a 20 element array, obviously c++ will error. I
need to figure out the size of this array.

I don't understand what you mean by "C++ will error." You have
an error, but it's all yours, and C++ may not detect it (It's not required
to) either at compile time or runtime.
 
Joined
Sep 20, 2008
Messages
11
Reaction score
0
All this talk about creating functions and extravagant steps....

I got frustrated after the first few posts, so I'll admit I didn't read everything that was written here, but I really don't think there's a lot someone needs to do for this check, and yes, it was a legit question.

If this is anything like what I was trying to do, which was to ensure that my users pass enough arguments into my program's parameters when they run it, then this is what they'd need to do, at least in C#:

To test if an argument exists, and that you don't get more than you should...

Code:
if ((args.Length >= 1) && (args.Length < 3))
{

// Then to build on that and do something with the arguments, since we know at least one argument exists....

     switch (args[0])
     {
       case "thisArgument":  // check the 1st argument slot
          if (args.Length > 1)  // check that we have a 2nd argument
          {
               string myTask = args[1];  // assign the 2nd argument
          }
          // and then do this
          break;
       case "thatOne":  // check the 1st argument slot
          if (args.Length > 1)  // check that we have a 2nd argument
          {
               string myJob = args[1];  // assign the 2nd argument
          }
          // and then do that
          break;
       default;
          Console.WriteLine("No valid argument.");
          break;
     }
}
else
{
     Console.WriteLine("This program requires at least one argument:  thisArgument or thatOne.  Please re-enter your choice.");
}

-Tom
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top