vectorをforでeraseするならiteratorは自己責任

remove_ifはbool func(const T& val)を定義する。 (c.f. sortはbool func(const T& l, const T& r)を定義)
・remove系はeraseの中で!
・forの中でeraseするなら、it++は付けずに、自分でイテレータを管理する。具体的には、if (do_erase()) it = erase(…); else it++;によってイテレータを更新。

#include <hamkoutil.hpp>
bool comp (const int& val) {return val % 2;}
main()
{
    vi a = {1, 2, 3, 4};
    a.erase(a.begin() + 2, a.end());
    print_vector(a);
    // -> 1 2

    vi b = {1, 2, 3, 4};
    b.erase(remove_if(b.begin(), b.end(), comp), b.end()); // removeはeraseの中で使うと良い
    print_vector(b);
    // -> 2 4

    vi c = {1, 2, 3, 4};
    for (auto it = c.begin(); it != c.end();) 
        if (*it % 2)
            it = c.erase(it, it + 1);
        else
            it++;
    // -> 2 4
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>