More Standard List Exercises
/* * Some more exercises with lists. */ #include <list> #include <iostream> using namespace std; /* * Print the contents of the list. Notice that, since we don't * change the list, it's sent as const reference. */ void print(const list<int> &list) { // The parameter is a plain int since we're not // changing the list. for(int i: list) cout << i << " "; cout << endl; } /* * Reverse the contents of the list. Notice that since we * do change the list, it's sent as plain reference. */ void reverse(list<int> &data) { list<int> backwards; // Drain list into backwards, reversing the order. while(!data.empty()) { // Put the first item from list onto the front of // backwards, then remove it from list. backwards.push_front(data.front()); data.pop_front(); } // Move the contents of backwards back into now-empty list. Using // swap avoids copying the list. data.swap(backwards); } int main() { // Lists (and vectors and other things) can be initialized with // a bracket-enclosed list. list<int> l1 = { 8, 7, 12, 22, 19, -17, 12, 3 }; print(l1); reverse(l1); print(l1); // Lists allow insertion. Insert adds in front of the indicated // location, but the iterator remains valid. So let's split all // the even ones. for(auto scan = l1.begin(); scan != l1.end(); ++scan) { if(*scan % 2 == 0) { auto half = *scan / 2; l1.insert(scan, half); *scan = half; } } print(l1); cout << endl; // You can also send a list initalizer as the value of a list // (or vector, etc) print({4, 9, 22, 1, 18}); cout << endl; // Let's try incrementing the contents of the list. for(int i: l1) { i++; } print(l1); // Since that didn't work, let's try it so that it does. // In the first one, each i value was a copy of the list // member. Here it's an alias. for(int & i: l1) { i++; } print(l1); }
This demonstrates the use of initializer lists (curly-brace lists) to give initial values for list, and also some things about the for-each construct.