/////////////////////////////////////////////////////////// // IteratorExamples.cpp - illustrate use of STL Iterator // // // // Jim Fawcett, CSE776 - Design Patterns, Summer 2009 // /////////////////////////////////////////////////////////// #include #include #include #include #include //#include ///////////////////////////////////////////////////////////////////////// // Please read this brilliant article on what is wrong with STL iterators // by one of the smartest authors around, Andre Alexandrescu // www.boostcon.com/site-media/var/sphene/.../iterators-must-go.pdf template void usesIterator(C& c) { typename C::iterator iter = c.begin(); std::cout << "\n "; while(iter != c.end()) std::cout << *iter++ << " "; iter = c.begin(); std::cout << "\n " << *iter; std::cout << "\n"; } void usesForeach(std::vector& tests) { class myOp { public: myOp() { std::cout << "\n "; } ~myOp() { std::cout << "\n--"; } void operator()(const std::string& s) { std::cout << s.c_str() << " "; } }; std::for_each(tests.begin(), tests.end(), myOp()); } template class myTemplateOp { public: myTemplateOp() { std::cout << "\n "; } ~myTemplateOp() { std::cout << "\n=="; } void operator()(const T& t) { std::cout << t << " "; } }; template void usesTemplateForeach(C& c) { std::for_each(c.begin(), c.end(), myTemplateOp()); } void main() { std::cout << "\n Demonstrating use of STL iterators"; std::cout << "\n ====================================\n"; std::string test[] = { "test1", "test2", "test3", "test4", "test5" }; std::cout << "\n Iterating through native array"; std::cout << "\n --------------------------------"; std::string* niter = &test[0]; std::cout << "\n "; while(niter != &test[5]) std::cout << *niter++ << " "; niter = &test[0]; std::cout << "\n " << *niter; std::cout << "\n"; std::cout << "\n Iterating through std::vector"; std::cout << "\n -------------------------------"; std::vector tests(&test[0],&test[5]); std::vector::iterator iter = tests.begin(); usesIterator(tests); std::cout << "\n Iterating std::vector with for_each and functor"; std::cout << "\n -------------------------------------------------"; usesForeach(tests); std::cout << "\n Iterating std::vector with for_each and template functor"; std::cout << "\n -----------------------------------------------------------"; usesTemplateForeach(tests); std::cout << "\n Iterating std::list with for_each and template functor"; std::cout << "\n --------------------------------------------------------"; int ints[] = { 1, 2, 3, 4, 3, 2 }; std::list lint(&ints[0], &ints[6]); usesTemplateForeach(lint); }