_STL ITERATORS_ by Dan Zigmond Listing One #include #include #include void main() { if (argc != 1) throw("usage: wc\n"); vector< string, less< string > > words; copy(istream_iterator< string >(cin), istream_iterator< string >(), inserter(words, words.end())); cout << "Number of words: " << words.size() << endl; } Listing Two #include #include #include void main() { if (argc != 1) throw("usage: uwc\n"); set< string, less< string > > words; copy(istream_iterator< string >(cin), istream_iterator< string >(), inserter(words, words.end())); cout << "Number of unique words: " << words.size() << endl; } Example 1: (a) char* find_char(char* first, char* last, const char& value) { while (first != last && *first != value) ++first; return first; } (b) template< class T > T* find_in_array(T* first, T* last, const T& value) { while (first != last && *first != value) ++first; return first; } (c) template struct list_node { list_node* next; T item; }; template T find_in_list(list_node* first, list_node* last, const T& value) { while (first != last && first->item != value) first = first->next; return first; } Example 2: template class list_node { public: list_node() : next(0) {} list_node(list_node< T >& ln) : next(ln.next), item(ln.item) {} ~list_node() { delete next; } list_node& operator=(const list_node& ln) { if (ln != this) { delete next; next = ln.next; item = ln.item; } return *this; } bool operator==(list_node ln) { return (item==ln.item && next==ln.next); } bool operator!=(list_node ln) { return (item!=ln.item || next!=ln.next); } T& operator*() { return item; } list_node operator++() { return *(next = next->next); } list_node operator++(int) { list_node tmp = *this; ++*this; return tmp; } private: list_node* next; T item; }; template< class T > list_node< T > find_in_list(list_node< T > first, list_node< T > last, const T& value) { while (first != last && *first != value) ++first; return first; } Example 3: template< class I, class T > I find(I first, I last, const T& value) { while (first != last && *first != value) ++first; return first; } Example 4: template DestinationIterator copy(SourceIterator first, SourceIterator last, DestinationIterator result) { while (first != last) *result++ = *first++; return result; } Example 5: (a) template ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value) { first = find(first, last, value); ForwardIterator next = first; return first == last ? first : remove_copy(++next, last, first, value); } (b) template OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value) { while (first != last) { if (*first != value) *result++ = *first; ++first; } return result; } Example 6: template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result; }