Remove an element and then erase that element : remove « STL Algorithms Modifying sequence operations « C++ Tutorial






/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>

/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;

    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;
}

/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}

using namespace std;

int main()
{
    vector<int> coll;

    INSERT_ELEMENTS(coll,2,6);
    INSERT_ELEMENTS(coll,4,9);
    INSERT_ELEMENTS(coll,1,7);
    PRINT_ELEMENTS(coll,"coll:               ");

    // remove all elements with value 5
    vector<int>::iterator pos;
    pos = remove(coll.begin(), coll.end(),   // range
                 5);                         // value to remove

    PRINT_ELEMENTS(coll,"size not changed:   ");

    // erase the ''removed'' elements in the container
    coll.erase(pos, coll.end());
    PRINT_ELEMENTS(coll,"size changed:       ");

}
coll:               2 3 4 5 6 4 5 6 7 8 9 1 2 3 4 5 6 7
size not changed:   2 3 4 6 4 6 7 8 9 1 2 3 4 6 7 5 6 7
size changed:       2 3 4 6 4 6 7 8 9 1 2 3 4 6 7








24.8.remove
24.8.1.Use the generic remove algorithm
24.8.2.Use std::remove to delete all element in a vector by value
24.8.3.Remove an element and then erase that element
24.8.4.Combine remove and erase together
24.8.5.Use remove() to delete elements from a vector
24.8.6.std::remove does not change the size of the container,it moves elements forward to fill gaps created and returns the new 'end' position.
24.8.7.Remove value from a vector with remove()