Re: std::list remove element mid iteration
On Dec 20, 12:40 pm, "cgsp...@gmail.com" <cgsp...@gmail.com> wrote:
On 12=E6=9C=8820=E6=97=A5, =E4=B8=8B=E5=8D=885=E6=97=B640=E5=88=86, James =
Kanze <james.ka...@gmail.com> wrote:
On Dec 20, 2:10 am, red floyd <no.s...@here.dude> wrote:
Christopher wrote:
The situation is that a std::list<std::set<std::string> > is being
iterated through. Upon certain criteria some sets become empty. I ne=
ed
to remove the empty sets from the list.
Is it safe to iterate through a list and call list::erase( iterator =
)
in mid iteration?
Well, you can use
struct set_is_empty
{
bool operator()(const std::set& s) const { return s.empty(); }
};
std::erase(std::remove_if(l.begin(), l.end(), set_is_empty());
Which could be unnecessarily expensive. In the case of
std::list, the canonical form is:
l.remove_if( set_is_empty() ) ;
That is what I found in MSDN,
remove_if is a STL algorithm which removes all elements from the range
(First,Last) that cause the predicate to return true. It returns an
iterator equal to Last - n, where n = number of elements removed. The
last n elements of the range have undefined values. The size of the
container remains the same.
But there is a method named remove_if in std::list.
template<class Predicate>
void remove_if(
Predicate _Pred
)
Erases elements from a list for which a specified predicate is
satisfied.
I didn't know there is a method named remove_if in the std::list. Can
any one told me why there is no similar method in vector ?
Because you don't need it, and it's not directly supported by
the underlying data structure.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=C3=A9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=C3=A9mard, 78210 St.-Cyr-l'=C3=89cole, France, +33 (0)1 30 23 00 3=
4