Home > Software engineering >  C problem adding elements to a std::list
C problem adding elements to a std::list

Time:06-06

I'm working on a project in which I have to assign missions to timetables. Timetables are divided in three classes : Semaine, Journee and Mission.Each class contains a list of elements of the lower level. Here's the definition of each class :

class Mission{}

class Journee{
    list<Mission> missions;
    bool addMission(Mission& m);
}

class Semaine{
    list<Journee> jours;
    bool addMission(Mission& m);
}

I want to add a Mission to an element of the list jours using Semaine::addMission(). However, when I try doing so, the added element doesn't appear, whereas it appears when I use Journee::addMission(). Here's the code of each addMission() function:

bool Semaine::addMission(Mission& m){
    if(!isInWeek(m.date)) return false;
    for(Journee j : jours){
        if(j.addMission(m)){
            initMemory(); // not important here
            return true;
    }
    return false;
}
bool Journee::addMission(Mission& m){
    if(m.date==date){
        missions.push_back(m);
        missions.sort();
        initMemory(); // same
        return true;   
    }
    return false;
}
// Alternative tries : change return types to Journee/Semaine and Journee&/Semaine&

Each call to these functions from the main file:

Semaine s = Semaine();
for(Mission m : missions) s.addMission(m);
cout << s; // Printed as if no mission was added

Semaine j = Journee();
for(Mission m : missions) j.addMission(m);
cout << j; // Printed with added missions

I understood that this kind of problem can occur when copy constructors are missing or bad, so I implemented one for each class, here they are (attributes of standard types copied with = operator):

Mission(const Mission& m){}
Semaine::Semaine(const Semaine& s){jours = list<Journee>(s.jours);}
Journee::Journee(const Journee& j){missions = list<Mission>(j.missions);}
//Alternative tries : std::copy, list::insert

Constructors used :

Journee::Journee(){missions = list<Mission>();}
Semaine::Semaine(){Semaine(1);}
Semaine::Semaine(int dateLundi){
    this->dateLundi = dateLundi;
    jours = list<Journee>();
    for(int i = 0; i < 7; i  ){
        jours.push_back(Journee(dateLundi i));
    }
}

Do you have any idea why is it not working/how to fix it?

CodePudding user response:

I think the problem is in

    for(Journee j : jours){

This gives you a copy of Journee.

Using a reference instead, i.e.

    for(Journee& j : jours){

should solve the problem

Similarly for

for(Mission m : missions) s.addMission(m);

That should rather be:

for(Mission& m : missions) s.addMission(m);

or even better:

for(auto& m : missions) s.addMission(m);
  • Related