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 = 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;
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.
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