Hey guys,

I was wondering if anybody knew of a method to check if an element in a object array was empty.
for example, lets say I have the class "XYZ"

class XYZ
{
    int x;
    string y;
};

then in main if i declared the object array:

int main()
{
    XYZ ar[10];
    return 0;
}

is it possible to check if a part of that array is empty?
for example:

for(int i = 0; i < 10; i++)
{
    if(ar[i].x != NULL) //is there anyway to make this comparison?
    { //CODE HERE }
}

Recommended Answers

All 3 Replies

Member Avatar for iamthwee

I guess you could initialise all 10 to contain a placeholder values.

When you loop through any which have actual values will show the other will have the placeholder values.

There may be other ways.

For that case you need to define what empty means. For example it could be this

struct Foo{
  int x;
  string y;
  Foo(): x(0), y(){};
}
//it is empty only if x == 0 and y contains no letter
bool isEmpty(const Foo& f){ return x == 0 && y.empty(); }

int main(){
   Foo f[10];
   bool isFirstElementEmpty = isEmpty( f[0] );
   return 0;
}

Another way is to use pointers.

 struct Foo{
   int x;
   string y;
   Foo(): x(0), y(){};
 }

 int main(){
   typedef boost::shared_ptr<Foo> FooPtr;
   FooPtr foo[10];
   bool isFirstElementEmpty = f[0].get() != NULL;
 }

thanks for the input guys, I'll try out your suggestions

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.