[ create a new paste ] login | about

Link: http://codepad.org/eV8pef8E    [ raw code | output | fork ]

C++, pasted on Jan 27:
#include <iostream>
#include <list>
#include <algorithm>
#include <memory>
//#include <cstdlib>
#include <stdlib.h>

//void *operator new(size_t size, const std::nothrow_t&) { std::cout << "new GLOBAL" << std::endl; return malloc(size); }
//void operator delete(void *p) { std::cout << "delete GLOBAL" << std::endl; free(p); }

class Hoge {
public:
  int *p;
  int nonexist;

  Hoge(int n) {
    this->p = new(std::nothrow) int;
    if (this->p)
      *(this->p) = n;
    nonexist = (n % 3 == 0) ? true : false;
  }
  ~Hoge() { delete p; }
//  static void *operator new(size_t size, const std::nothrow_t&) { std::cout << "new Hoge()" << std::endl; return malloc(size); }
//  static void operator delete(void *p) { std::cout << "delete Hoge()" << std::endl; free(p); }
};

// not used <functional>
class EraseP {
public:
  bool operator()(Hoge *p) {
    bool b;
    if ((b = p->nonexist) == true) delete p;
    return b;
  }
};

class Show {
public:
  void operator()(Hoge *c) { std::cout << *(c->p) << std::endl; }
};

int main() {
  std::list<Hoge *> mylist;
  for (int i = 0; i < 10; i++)
    mylist.push_back(new(std::nothrow) Hoge(i));


  for_each(mylist.begin(), mylist.end(), Show());
//  mylist.remove_if(EraseP());
  mylist.erase(remove_if(mylist.begin(), mylist.end(), EraseP()), mylist.end());
  for_each(mylist.begin(), mylist.end(), Show());
  while (!mylist.empty()) {
    std::list<Hoge *>::iterator p = mylist.begin();
    delete *p;
    mylist.pop_front();
  }
  
  return 0;
}
/* end */


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
0
1
2
3
4
5
6
7
8
9
1
2
4
5
7
8


Create a new paste based on this one


Comments: