|
![](/i/fill.gif) |
Thorsten Froehlich <tho### [at] trf de> wrote:
:> And iterators are just brilliant.
: It is easy to make the wrong assumptions about them, i.e. how fast they
: really are for some data structures. Nevertheless, they are really useful!
It's the idea behind the iterators that make them so brilliant.
They work like pointers (but are of course much safer). This means that
you can read the same data container from different places using different
iterators without them interfering each other.
A mistake made often by people is to create a data container and then
add some methods like "getFirst()" and "getNext()". This has the serious
problem that you can't read the container from different places without
each of them interfering the others. But as iterators work like pointers,
they can be used independently.
Also iterators are very independent of the data container they are
associated to. This means that you don't have worry how to get to the next
item; you just make a ++ and you are in the next item, no matter if the
container is a list, a vector, a tree or whatever.
This means that general algorithms that work for most STL containers can
be made (and they have been made in the <algorithm> include file).
For example if you want to sort your items you just call:
sort(myCont.begin(), myCont.end());
It doesn't matter if myCont is a vector, a list, a deque or whatever (for
binary trees it makes no sense since they are already sorted; also the STL
list has an inner sort which is more efficient since it only changes
pointers and doesn't need to copy the items, but the above command should
work for lists as well).
If you want to sort your container in reverse order, it's easy:
sort(myCont.rbegin(), myCont.rend());
(Btw, the fact that rbegin() returns an iterator to the same item as end()
and that rend() returns an iterator to the same item as begin() is very
confusing until you understand how they really work.)
Also copying data from one container to other is very easy. For example:
vector<int> myVector(myCont.begin(), myCont.end());
It doesn't matter what myCont is, as long as its iterator supports
operator++().
This last thing is specially useful in this case:
int main(int argc, char* argv[])
{ vector<string> CommandLine(argv, argv+argc);
This is so because regular pointers work as iterators as well (not a
big surprise).
--
main(i,_){for(_?--i,main(i+2,"FhhQHFIJD|FQTITFN]zRFHhhTBFHhhTBFysdB"[i]
):_;i&&_>1;printf("%s",_-70?_&1?"[]":" ":(_=0,"\n")),_/=2);} /*- Warp -*/
Post a reply to this message
|
![](/i/fill.gif) |