How to remove a struct record from an STL list

前端 未结 1 1015
灰色年华
灰色年华 2021-01-29 11:01

I have a list of type struct and I want to remove a specific record from that list. What is the best way to do this? I cannot figure out how to do it with .re

相关标签:
1条回答
  • 2021-01-29 12:01

    This is the reference you need to understand for std::list::remove() - http://en.cppreference.com/w/cpp/container/list/remove

    If you had a list of something like int then just remove() would work. In your case though your list contains a struct with no equality operator defined for it. The equality operator is how remove() will know when the param passed in matches what's in the list. Note: this will remove all elements that match, not just one.

    Your struct with an equality operator would looks something like this:

    struct dat
    {
        string s;
        int cnt;
    
        bool operator==(const struct dat& a) const
        {
             return ( a.s == this->s && a.cnt == this->cnt )
        }
    };
    

    Alternately you can remove elements from a list by iterator. In that case you would use erase().

    It really depends on what you're trying to do and why you've chosen to use a std::list. If you're not familiar with these terms then I'd recommend reading up more first.

    0 讨论(0)
提交回复
热议问题