Skip to content

Instantly share code, notes, and snippets.

@yoggy
Created February 21, 2014 11:04
Show Gist options
  • Save yoggy/9132509 to your computer and use it in GitHub Desktop.
Save yoggy/9132509 to your computer and use it in GitHub Desktop.
いつも忘れるのでメモ。
//
// stl-erase-sample.cpp - erase() sample for STL container
//
// $ g++ stl-erase-sample.cpp && ./a.out
// ==== before ====
// 1
// 2
// 2
// 3
// 3
// ==== after ====
// 1
// 3
// 3
//
#include <iostream>
#include <list>
#include <algorithm>
class print_list {
public:
void operator()(const int &val) {
std::cout << val << std::endl;
}
};
int main(int argc, char *argv[])
{
std::list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(2);
l.push_back(3);
l.push_back(3);
std::cout << "==== before ====" << std::endl;
std::for_each(l.begin(), l.end(), print_list());
// erase sample...
std::list<int>::iterator it = l.begin();
while(it != l.end()) {
if (*it == 2) {
it = l.erase(it);
}
else {
++it;
}
}
std::cout << "==== after ====" << std::endl;
std::for_each(l.begin(), l.end(), print_list());
return 0;
}
~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment