Using remove_if() within lists.

closed account (Sw07fSEw)
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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <string>
#include <forward_list>
using namespace 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"?
Last edited on
See this:

http://www.cplusplus.com/reference/forward_list/forward_list/remove_if/

You need to provide a function with Reservation as paramter and bool as the result type.
How do I write this expression?
reservations.remove_if(this->getName() == "Eric");


reservations.remove_if([](Reservation& r) { return r->getName() == "Eric"; });

http://www.drdobbs.com/cpp/lambdas-in-c11/240168241
Topic archived. No new replies allowed.