C++ examples for STL:list
Storing Objects in a list
#include <iostream> #include <list> #include <string> #include <algorithm> using namespace std; template<typename T> struct printer {//w w w . ja v a 2 s . com void operator()(const T& s) { cout << s << '\n'; } }; bool inline even(int n) { return(n % 2 == 0); } printer<string> strPrinter; printer<int> intPrinter; int main() { list<string> lstOne; list<string> lstTwo; lstOne.push_back("Red"); lstOne.push_back("Green"); lstOne.push_back("Blue"); lstTwo.push_front("A"); lstTwo.push_front("B"); lstTwo.push_front("C"); for_each(lstOne.begin(), lstOne.end(), strPrinter); lstOne.sort(); // list has a member for sorting lstTwo.sort(); lstOne.merge(lstTwo); // Merge the two lists and print for_each(lstOne.begin(), lstOne.end(), strPrinter); list<int> intLst; intLst.push_back(0); intLst.push_back(1); intLst.push_back(2); intLst.push_back(3); intLst.push_back(4); for_each(intLst.begin(), intLst.end(), intPrinter); // Or, remove all even values intLst.remove_if(even); }