class SIterator { SNode *current; public: SIterator(SNode *s) : current(s) { } const string& next() const { return current->item; } bool hasNext() const { return current != nullptr; } void operator++() // PREINCREMENT operator { assert(hasNext()); current = current->next; } };
class SList { public: ... SIterator iterator() const { return SIterator(head); } ... };
SList names; ... add items to names for(SIterator it = names.iterator(); it.hasNext(); ++it) { SIterator dup_it = it; if ( dup_it.hasNext() ) ++dup_it; // skip past current item in list while ( dup_it.hasNext() && it.next() != dup_it.next() ) ++dup_it; if ( dup_it.hasNext() ) // stopped because found item cout << "Duplicate entry in list: " << dup_it.next() << endl; }
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; 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;
vector<float> sizes; ... code to read sizes ... sort(sizes.begin(), sizes.end()); // O(N log N) reverse(sizes.begin(), sizes.end());
float nums[50]; ... code to read numbers ... sort(&nums[0], &nums[50]);Note how the address of the element just past the last array element was used to mark the array end.