How do I efficiently remove_if only a single element from a forward_list?

后端 未结 5 1298
灰色年华
灰色年华 2021-01-18 03:00

Well I think the question pretty much sums it up. I have a forward_list of unique items, and want to remove a single item from it:

std::forward_list         


        
5条回答
  •  天涯浪人
    2021-01-18 03:18

    There is nothing in the standard library which would be directly applicable. Actually, there is. See @TemplateRex's answer for that.

    You can also write this yourself (especially if you want to combine the search with the erasure), something like this:

    template 
    bool remove_first_if(std::forward_list &list, Predicate pred)
    {
      auto itErase = list.before_begin();
      auto itFind = list.begin();
      const auto itEnd = list.end();
      while (itFind != itEnd) {
        if (pred(*itFind)) {
          list.erase_after(itErase);
          return true;
        } else {
          ++itErase;
          ++itFind;
        }
      }
      return false;
    }
    

提交回复
热议问题