I spent the past hour reading up on how to use the remove_if() function on the list and forward_list containers. However, I'm having trouble translating their properties to lists of objects. I have a larger existing project that I think would be much more efficient if I use the remove_if() function instead of my existing code.
I came up with pretty basic example to ask my question so I can translate the same concept to my larger project. I have a class called Reservation, for the example we'll say Reservation has two instance variables of type string called date and name. I built some accessor functions to get the values of those variables to use throughout my program. Now my question is, how do I use remove_if() to remove objects based on the values of their instance variables? I wrote what I thought was a valid expression in line 35 of the sample code below, but I'm having trouble referencing the private 'date' member of each object. I thought the keyword 'this' would work because remove_if() removes all elements in the container if the condition is true. In my scenario each element is an object so I need to be able to access the instance variables of each object. Would I maybe need to use an iterator instead?
#include <iostream>
#include <string>
#include <forward_list>
usingnamespace std;
class Reservation{
private:
string date;
string name;
public:
Reservation(string name);
string getDate();
string getName();
};
Reservation::Reservation(string name){
this->name = name;
}
string Reservation::getDate(){
return date;
}
string Reservation::getName(){
return name;
}
forward_list<Reservation> reservations; // global list
int main(){
Reservation res_1("Eric"); // create two instances
Reservation res_2("Colin");
reservations.push_front(res_1); // add them to the list
reservations.push_front(res_2);
reservations.remove_if(this->getName() == "Eric"); // how do I write this expression?
return 0;
}
So again, my question is, how can I remove objects based off of conditions from their instance variables? If I had 1000 Reservation objects in a foward_list, how could I remove all of the instances from the list where the private variable date equals "Monday"?