R L W
R L W

Reputation: 135

How can I test whether an array element is defined or not (where element can be defined as 0)?

DISCLAIMER: I'm very new to C++ so I'm sorry if this is a stupid question!

I'm trying to read in data to an 1000 element array (double) and then if there are less than 1000 data points to read in ignore the excess elements for the rest of my program.

I've defined a 1000 element array and read in the data and now want to carry out a function on each element which has been defined by the read in data point. How do I test if an element is defined yet? I would use a Boolean algebra test i.e. if(array[i]) {\\function} but the data points can be any natural number including zero, so I don't know if this would work. How would I solve this problem?

Upvotes: 0

Views: 172

Answers (2)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

You could initialize your array with a sentinel value like NAN (i.e., not a number):

double array[1000];
std::fill(std::begin(array), std::end(array), NAN);

Then fill sequentially your array:

array[0] = 1.2;
array[1] = 2.3;
array[2] = 3.4;

And then break the loop as soon as this value is met:

for(int i(0); i < 1000; ++i) {
  if(isnan(array[i])) break;
  function(array[i]);
}

LIVE DEMO

Upvotes: 0

user1084944
user1084944

Reputation:

The most typical approach to the problem of "the number of things in my array is not fixed ahead of time" is to have a variable that keeps track of how many things are actually in the array. Then, you just loop over that many things.

Since you add the C++ tag, you can (and should) use the vector class to manage everything for you — and you even get the added benefit that it can grow beyond 1000 elements should you happen to have more than that.

(aside: if you insist on sticking with a 1000-long array, you really should make sure you do something appropriate should you actually get more than 1000 data points)

Upvotes: 2

Related Questions