C++ list loop via while statement
#include <iostream> #include <list> using namespace std; class Duck//from w ww . j a v a 2 s . com { public: string name; int weight; int length; }; ostream& operator << (ostream &out, const Duck &duck) { cout << "(" << duck.name; cout << "," << duck.weight; cout << "," << duck.length; cout << ")"; return out; } void DumpDucks(list<Duck> *mylist) { list<Duck>::iterator iter = mylist->begin(); while (iter != mylist->end()) { cout << *iter << endl; iter++; } } list<Duck>::iterator MoveToPosition(list<Duck> *mylist, int pos) { list<Duck>::iterator res = mylist->begin(); for (int loop = 1; loop <= pos; loop++) { res++; } return res; } int main() { list<Duck> duckList; // Push some at the beginning Duck d1 = {"J", 20, 15}; // Braces notation! duckList.push_front(d1); Duck d2 = {"S", 15, 12}; duckList.push_front(d2); // Push some at the end Duck d3 = {"S", 18, 25}; duckList.push_front(d3); Duck d4 = {"T", 19, 26}; duckList.push_front(d4); Duck d5 = {"S", 12, 13}; duckList.push_front(d5); // Display the ducks DumpDucks(&duckList); // Reverse duckList.reverse(); DumpDucks(&duckList); // Splice // Need another list for this list<Duck> extras; Duck d6 = {"G", 8, 8}; extras.push_back(d6); Duck d7 = {"S", 8, 8}; extras.push_back(d7); Duck d8 = {"O", 8, 8}; extras.push_back(d8); Duck d9 = {"G", 8, 8}; extras.push_back(d9); DumpDucks(&extras); list<Duck>::iterator first = MoveToPosition(&extras, 1); list<Duck>::iterator last = MoveToPosition(&extras, 3); list<Duck>::iterator into = MoveToPosition(&duckList, 2); duckList.splice(into, extras, first, last); DumpDucks(&extras); DumpDucks(&duckList); return 0; }