Skip to content

Instantly share code, notes, and snippets.

@sansumbrella
Forked from cporter/remove_if.cpp
Created November 26, 2012 15:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sansumbrella/4148757 to your computer and use it in GitHub Desktop.
Save sansumbrella/4148757 to your computer and use it in GitHub Desktop.
remove_if and vector
// -*- compile-command: "clang++ -std=gnu++0x -stdlib=libc++ -o remove_if remove_if.cpp" -*-
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
int main (int, char **) {
std::vector<int> ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "Range-based for loop:" << endl;
cout << ints . size () << " elements in ints" << endl;
// will remove
for( auto &x : ints )
{
ints.erase( remove_if( ints.begin()
, ints.end()
, [=](const int y){ return x == y; } )
, ints.end() );
// And yet this will happen ten times!
cout << x << endl;
}
cout << ints . size () << " elements in ints" << endl;
ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cout << "Traditional iterator-based for loop:" << endl;
cout << ints . size () << " elements in ints" << endl;
for( auto x = ints.begin(); x < ints.end(); ++x )
{
ints.erase( remove_if( ints.begin()
, ints.end()
, [=](const int y){ return *x == y; } )
, ints.end() );
// And yet this will happen ten times!
cout << *x << endl;
}
cout << ints . size () << " elements in ints" << endl;
cout << "Range-based for loop on copy:" << endl;
ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto ints_copy = ints;
for( auto x : ints_copy )
{
ints.erase( remove_if( ints.begin()
, ints.end()
, [=](const int y){ return x == y; } )
, ints.end() );
cout << x << endl;
}
cout << ints.size() << " elements in ints" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment