I have this interesting assignment where I have a std::map
of CTurist
(previous class) and unsigned
variable. Here's the code:
class CTurist
{
protected:
string tName;
int age;
public:
CTurist() {};
CTurist(string name, int age2)
{
tName = name;
age = age2;
}
bool operator<(const CTurist& e) const
{
return age < e.age;
}
friend ostream& operator<<(ostream& os, const CTurist&& e);
friend ifstream& operator>>(ifstream& is, CTurist&& e);
};
class CHotel:public CTurist
{
protected:
string hName;
int stars;
int beds;
map<CTurist, unsigned> Turisti;
public:
unsigned Sum = 0;
CHotel(){};
CHotel(string hName2, int zvezdi, int legla)
{
hName = hName;
stars = zvezdi;
beds = legla;
}
int Compare()
{
list<CTurist*> list;
int br=0;
CTurist vyzrast;
map<CTurist, unsigned>::iterator it = Turisti.begin();
while (it != Turisti.end())
{
if (it->first < vyzrast)
{
br++;
}
else
{
list.push_back(std::move(&it->first));
}
}
}
};
I know it's quite a long one, but I thought it's best to give you all the information.
Now, the int Compare()
function AT THE BOTTOM is the one causing me problems.
I have to check if the age of the tourists is above or below a parameter which I've called vyzrast
here. We're comparing the age
. If it's below, it's quite straight forward.
If it's above though, I have to add those Tourists to a list<CTurist*>
, aka. to a list of pointers. If I make the list from objects, not pointers. No luck with this, hence why I'm looking for suggestions how to fix it here.
Why are you using rvalue references for your
operator
overloads? You should be usingconst CTurist &
foroperator<<
andCTurist&
foroperator>>
. And you should be usingstd::istream
foroperator>>
:Aside from that, there is no reason for
Compare()
to usestd::move()
at all when populating thestd::list
, as it is adding pointers, not moving actual objects.Compare()
doesn't won't correctly for several reasons:it->first
is an actualconst CTurist
object, but yourstd::list
is expectingCTurist*
pointers.std::map
keys areconst
, so&it->first
is aCTurist const *
pointer (non-const pointer to const object), not aCTurist*
pointer (non-const pointer to non-const object) like you are expecting.Your
vyzrast
object is uninitialized. You are not assigning any value to itsage
(andtName
) member at all, so the result of your comparisons is indeterminate.You are not incrementing your
it
iterator on each loop iteration, so you are stuck in an infinite loop if thestd::map
is not empty.Try something more like this instead:
Live Demo