Re: Confusion with iterator
"pandit" <jalaf28@gmail.com> wrote in message
news:82f808f4-aa38-4139-b456-3cd82afd6b76@d21g2000prf.googlegroups.com...
Hello i dont understand how to Deal with iterator. its little bit
confusing ?
how they work??
iterators are for _iterating_ through a container. I wouldn't worry about
how they work, but I'd learn how to use them.
Just think of it as a "special" kind of pointer to an element in a
container. You do not know how the underlying implementation of the
container works, so they provide you with a way to access an element no
matter how it has been allocated.
Almost all stl containers have a begin() and end() method.
If you visualize your stl container like an array, then begin points to
element [0] and end points to the next element out of bounds.
example:
#include<vector>
#include <iostream>
int main()
{
std::vector<int> bunchonumbers;
// Fill it up with numbers
for(int i =0; i < 5; i++)
bunchonumbers.pushback(i);
// Visualize an array [0][1][2][3][4]
// Now you can _iterate_ through it
// begin points to element [0]
// end points to some memory after [4], containing something unknown
// notice how you can perform arithmetic just like pointers: it++
for( std::vector<int>::iterator it = bunchonumbers.begin(); it !=
bunchonumbers.end(); it++)
{
// Notice how you can dereference the iterator just like a pointer
std::cout << *it;
}
return 0;
}
Iterators are just a special way of accessing elements in a container.
There is more to iterators than that, but it is the basics. For example,
there are different flavors of iterators with different rules, but that
comes later.