STL General: How to remove elements of a particular value from a container ?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: STL General: How to remove elements of a particular value from a container ?

Threaded View

  1. #1
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588

    STL General: How to remove elements of a particular value from a container ?

    Q: What is the best way to remove all elements of a particular value from a container?

    A: Use the so-called 'remove/erase' idiom:

    Code:
    // taken from Item 32 of Scott Myers' Effective STL
    vector<int> v;
    v.erase(remove(v.begin(), v.end(), 99), v.end());
    This is because of the simple fact that 'remove()' is a generic algorithm which takes iterators as its arguments. The iterators know nothing of their container; the STL was designed so as to grant the smallest possible amount of coupling. Thus, the iterators cannot call any container's 'erase()' or similar function.

    'remove()' DOES return the container's new 'end()' (which just
    happens to be the first element that was removed) and this value
    can be used in the container's 'erase()' call.


    Last edited by Andreas Masur; July 24th, 2005 at 12:59 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center