index VS iterator

Dear all,
I cannot really get the significance of iterators. Illustrating below:

vector<int> V;
using std::vector<int>::iterator iter;

OPTION 1:
for (iter = V.begin(); iter!=V.end(); iter++)
{do something};

OPTION 2:
for (int i=0; i<V.size(); i++)
{do something};

I suppose option 1 and option 2 are the same. In this case why should I bother defining an iterator when I can essentially do the same thing by a simple integer index? What exactly is the significance of an iterator??? Thanks in advance for anyone who could illustrate its power to me.

Regards,
Bosco
The big advantage with iterators is that they work with all containers. Index works with just a few containers like vector and deque.
An iterator is a generic term for something that can traverse a container. Consider this function:
1
2
3
4
5
6
std::ostream& println(std::ostream& os, container_type &c)
{
    for (container_type::const_iterator p = c.begin(); p != c.end(); ++p)
        os << *p << std::endl;
    return os;
}

This will work with any of these typedefs:
 
typedef std::map<int, std::string> container_type;
or
 
typedef std::vector<int> container_type;
or
 
typedef std::set<int> container_type;


The index operator is a feature of arrays and is not common to all containers.

Having this common technique for traversing different containers allows algorithms to be written that work across a range of containers. It's a fundamental principle that allows STL to reduce the number of functions it implements.
Last edited on
Hmm... Thanks guys in that case I guess that's only because I am new to container class and so I cannot get the significance of iterators.

Another question in this case... I am currently reading the introductory C++ book written by Walter Savitch called "Problem Solving with C++". Is there any books that you can recommend which I can study the different container class in depth?? (But note that my C++ is only on the introductory level...)

Regards,
Bosco
You would need to understand templates first. It's straight forward in principle, but can get complicated quickly.

I found that the easiest way to understand some of this stuff is to look at the source code. Now, the STL container code isn't trivial, but that's where you could begin.

Take a look at vector and vector's iterator. If you understand how to implement a double threaded linked list, take a look at list and list's iterator.

And finally, take a look at string's implementation, basic_string. It uses a trait pattern, which is an interesting approach. You should try to understand traits before you look at this one so you understand what effect the code is trying to achieve.
http://en.wikipedia.org/wiki/Traits_%28computer_science%29
Last edited on
Topic archived. No new replies allowed.