B
Ben
Hi all,
I'm not yet good at thinking the right way in c++ so although I could
solve this problem, I'm not sure if they way I'm thinking of is the best
way to do it. I need a data type or class or something that can hold
either an int, or a float, knows which one it is holding, and will allow
me to do comparisons with instances of it without the code which asks
for the comparison having to know which one it is. So maybe I could do
it something like this (haven't compiled it so there are probably little
errors but hopefully you get the gist):
class Int_or_float {
int i;
float f;
bool is_int;
public:
bool Int_or_float:
perator==( Int_or_float &a ) {
if( this->is_int ) return this->i == a.i;
else return this->f == a.f;
}
}
I could do it more simply perhaps like this:
class Int_or_float {
public:
int i;
float f;
bool is_int;
}
bool equal( Int_or_float x, y ) {
if( x.is_int ) return x.i == y.i;
else return x.f == y.f;
}
I realise neither of these will behave well if you compare one storing
an int with one storing a float.
So what are the pros and cons of each method? Is there an even simpler
method? I hoped I might be able to use a union but I can't think how. I
suppose if I want to use the STL I have no choice but to use the first
way?
Thanks in advance,
Ben
I'm not yet good at thinking the right way in c++ so although I could
solve this problem, I'm not sure if they way I'm thinking of is the best
way to do it. I need a data type or class or something that can hold
either an int, or a float, knows which one it is holding, and will allow
me to do comparisons with instances of it without the code which asks
for the comparison having to know which one it is. So maybe I could do
it something like this (haven't compiled it so there are probably little
errors but hopefully you get the gist):
class Int_or_float {
int i;
float f;
bool is_int;
public:
bool Int_or_float:
if( this->is_int ) return this->i == a.i;
else return this->f == a.f;
}
}
I could do it more simply perhaps like this:
class Int_or_float {
public:
int i;
float f;
bool is_int;
}
bool equal( Int_or_float x, y ) {
if( x.is_int ) return x.i == y.i;
else return x.f == y.f;
}
I realise neither of these will behave well if you compare one storing
an int with one storing a float.
So what are the pros and cons of each method? Is there an even simpler
method? I hoped I might be able to use a union but I can't think how. I
suppose if I want to use the STL I have no choice but to use the first
way?
Thanks in advance,
Ben