-
-
Save sansumbrella/4148757 to your computer and use it in GitHub Desktop.
remove_if and vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -*- 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