class SList { struct SNode { string item; SNode *next; SNode(const string &s, SNode *n) : item(s), next(n) { } } *front; public: class iterator { SNode *current; public: iterator(SNode *start) : current(start) { } void operator++() // prefix version! { current = current->next; } string& operator*() // de-reference (since no parameters) { return current->item; } bool operator==(const iterator &other) { return current == other.current; } bool operator!=(const iterator &other) { return current != other.current; } }; // end of iterator iterator begin() { return iterator(front); } iterator end() { return iterator(nullptr); } ... other List operations to add/remove items ... };
list<double> nums; ... double sum = 0.0; for(auto it = nums.begin(); it != nums.end(); ++it) sum += *it;
list<string> todo; ... // find first "go to class", of amu list<string>::iterator pos = todo.begin(); // better: auto pos = todo.begin(); while ( pos != todo.end() && *pos != "go to class" ) ++pos; if ( pos != todo.end() ) cout << "Found it.";
int empty_count = 0; for(const auto& item : todo) if ( item.empty() ) ++empty_count;
std::list<int> l = {3,-1,10}; std::sort(l.begin(), l.end()); // not legal: cannot index a linked list; should use merge sort //Typical compiler diagnostic without concepts: // invalid operands to binary expression ('std::_List_iterator<int>' and // 'std::_List_iterator<int>') // std::__lg(__last - __first) * 2); // ~~~~~~ ^ ~~~~~~~ // ... 50 lines of output ... // //Typical compiler diagnostic with concepts: // error: cannot call std::sort with std::_List_iterator<int> // note: concept RandomAccessIterator<std::_List_iterator<int>> was not satisfied