Skip to content

Instantly share code, notes, and snippets.

@cporter
Created November 26, 2012 06:46
Show Gist options
  • Save cporter/4146904 to your computer and use it in GitHub Desktop.
Save cporter/4146904 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>
int main (int, char **) {
std::vector<int> ints = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// won't remove
for (auto &x : ints) {
// The following doesn't change ints at all, even though it
// hits one every element
auto it = remove_if (ints . begin (),
ints . end (),
[](const int y) { return true; });
std::cout << x << std::endl;
}
std::cout << ints . size () << " elements in ints" << std::endl;
// will remove
for (auto &x : ints) {
auto it = remove_if (ints . begin (),
ints . end (),
[](const int y) { return true; });
ints . resize (it - ints . begin ());
// And yet this will happen ten times!
std::cout << x << std::endl;
}
std::cout << ints . size () << " elements in ints" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment