fork(1) download
  1. #include <vector>
  2. #include <iostream>
  3. #include <boost/shared_ptr.hpp>
  4. #include <boost/iterator/filter_iterator.hpp>
  5. #include <boost/foreach.hpp>
  6. #include <boost/make_shared.hpp>
  7. using namespace std;
  8. using namespace boost;
  9.  
  10. struct Contact{
  11. int n;
  12. Contact(int x) : n(x) {}
  13. bool isReal(){ return n%2; } // the role of isReal will be played by isOdd
  14. };
  15.  
  16. struct ContactContainer{
  17.  
  18. // this is the underlying container
  19. typedef vector<shared_ptr<Contact> > ContainerT;
  20. ContainerT data;
  21.  
  22. // predicate defining whether we skip this contact or not
  23. struct IsReal{
  24. bool operator()(shared_ptr<Contact>& c){ return c && c->isReal(); }
  25. bool operator()(const shared_ptr<Contact>& c){ return c && c->isReal(); }
  26. };
  27.  
  28. typedef boost::filter_iterator<IsReal,ContainerT::iterator> iterator;
  29. typedef boost::filter_iterator<IsReal,ContainerT::const_iterator> const_iterator;
  30.  
  31. // return proxy iterator
  32. iterator begin(){ return iterator(data.begin(), data.end()); }
  33. iterator end(){ return iterator(data.end(), data.end());}
  34. const_iterator begin() const { return const_iterator(data.begin(), data.end()); }
  35. const_iterator end() const { return const_iterator(data.end(), data.end()); }
  36. size_t size() const { return data.size(); }
  37. };
  38.  
  39.  
  40. int main()
  41. {
  42. ContactContainer contacts;
  43. contacts.data.push_back(make_shared<Contact>(1));
  44. contacts.data.push_back(make_shared<Contact>(2));
  45. contacts.data.push_back(make_shared<Contact>(3));
  46. contacts.data.push_back(make_shared<Contact>(4));
  47. contacts.data.push_back(make_shared<Contact>(5));
  48. contacts.data.push_back(make_shared<Contact>(6));
  49. BOOST_FOREACH(const shared_ptr<Contact>& c, contacts){
  50. std::cout << "Iterating, c->n = " << c->n << "\n";
  51. };
  52. }
  53.  
Success #stdin #stdout 0s 2860KB
stdin
Standard input is empty
stdout
Iterating, c->n = 1
Iterating, c->n = 3
Iterating, c->n = 5