-
iterator
I have found the following code :
Code:
#include <algorithm>
#include <iostream>
#include <list>
#include <set>
#include <string>
using namespace std;
int main()
{
typedef set<string> WordSet;
typedef WordSet::iterator WordIter;
typedef list<WordIter> Index;
WordSet words;
Index input_order;
// Input the words uniquely
for(string new_word; cin >> new_word, new_word!="Quit"; )
{
pair<WordIter, bool> const &trace = words.insert(new_word);
if (trace.second)
input_order.push_back(trace.first);
}
// Output unique words in order of input:
cout << "\n>>> Unique words in input order:\n";
for (Index::iterator p = input_order.begin(); p!=input_order.end(); ++p)
{
cout << *(*p) << '\n';
}
// Output unique words in default set<string> order:
cout << "\n>>> Unique words in sorted order:\n";
copy(words.begin(), words.end(), ostream_iterator<string>(cout, "\n"));
return 0;
}
what is the iterator thing?
Is it like a cin or just a variable that holds a value? .. or something else?
Luigi
-
think of it as an object that acts like a glorified generalization of a pointer and you will be pretty close.
-
re:iterator
is iterator part of the stl?
i mean in <set> maybe?
Luigi
-
yes, I've never seen iterators (as such) used outside of STL (I have seen smart pointers which are similar to iterators outside of STL). Iterators are objects and need to be declared for each container they are associated with. While you can write your own iterator class, the containers in STL come with their own. Unlike pointers, iterators come in a variety of flavors such as forward iterators, reverse iterators, bidirectional iterators, etc. For straightforward application of the concept you can just declare an iterator using syntax similar to that in the code you provided and get by with it. With more sophisticated applications the full flexibility of iterators becomes more relevant. You can read about iterators in any text that talks about STL containers.
-
When we iterate through a list for instance, we usually have to reference the node through which the data is stored.
if(iter->data > 10)
iter->data = 0;
iter = iter->next;
Iterators overload the traversing pointer to return a pointer to the data. Also, the iterator is overloaded with the post/pre increment/decrement operators to further abstract the implementation:
if( *iter > 10 )
*iter = 0;
iter++;