lundi 19 avril 2021

C++ change list while iterating?

In C++11 have a list called jobs, in which I want to delete all jobs with stopped flag being true, so I wrote:

auto job = jobs.begin();
while (job != jobs.end()) {
    if (!job->stopped) {
        job = jobs.erase(job)
    } else {
        ++job;
    }
}

But someone took a look at my code and said it's wrong which I doin't understand why?


my class:

class JobsList {
public:
    class JobEntry {
    public:
        pid_t pid, jid;
        string cmd;
        time_t in_time;
        bool stopped;

        JobEntry(int pid, int jid, string &cmd, bool stopped);
        // TODO: Add your data members

        bool operator<(JobEntry const &tmp) const {
            return jid < tmp.jid;
        }

        bool operator==(JobEntry const &tmp) const {
            return jid == tmp.jid;
        }
    };

    std::list<JobEntry> jobs;
};

Aucun commentaire:

Enregistrer un commentaire