I want to iterate through a list of objects, then erase all objects from the list which meet a certain criteria. Here is an example using int type as my object:

list<int> m_list;
        // Fill list with int values...

        // Find ints == 4 and erase them
	auto it = m_list.begin();
	if (*it == 4)
	{
		it = m_list.erase(it);
	}
	while (it != m_list.end())
	{
		++it;
		if (*it == 4)
		{
			it = m_list.erase(it);
		}
	}

This code works fine, but it seems wordy and the iterator it is still in scope after I am through with it.

I thought I should be able to use a for loop like this:

for (auto it = m_list.begin(); it != m_list.end(); ++it)
	{
		if (*it == 4)
		{
			it = m_list.erase(it);
		}
	}

But when the last element in the list is erased, .erase returns an iterator to the end of the list which cannot be incremented.

So is there a better way to erase? Thank you.

Recommended Answers

All 6 Replies

std::list has a remove_if method. Check it out

commented: ah yep, that's the trick +2

While you are using C++0x, then you might as well do:

my_list.remove_if( [](int x) -> bool { return x == 4; } );
commented: ah, right lambdas! thank you +2

While you are using C++0x, then you might as well do:

my_list.remove_if( [](int x) -> bool { return x == 4; } );

Hey mike the "-> bool" specifies a return type?

>>Hey mike the "-> bool" specifies a return type?

Yeah, that's the Lambda expression syntax.

It is also a new way to specify return types for normal functions, with the "auto" keyword. As so:

auto my_function() -> int {
  //..
};

This is especially useful for function and class templates where the return type can be contingent on the parameter types in a non-trivial way.

>>Hey mike the "-> bool" specifies a return type?

Yeah, that's the Lambda expression syntax.

It is also a new way to specify return types for normal functions, with the "auto" keyword. As so:

auto my_function() -> int {
  //..
};

This is especially useful for function and class templates where the return type can be contingent on the parameter types in a non-trivial way.

thx.

Also note that the lambda return type can be deduced in this case, explicitly specifying it is unnecessary:

my_list.remove_if([](int x) { return x == 4; });
commented: Already an expert in C++0x... you're awesome! +11
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.