-3

Is it true that index is a member function that can return the value of an element in a container and an iterator is a value that can access, move through and move through a container?

Dog
  • 33
  • 2

1 Answers1

2

An index (or key) is used to look up data in a container. The simplest case would be the integer indexes of an array, but containers like std::map can have nearly any type as an index.

An iterator is a class which represents a position in a container. They might be obtained from accessing a container with an index/key, such as iterator std::map::find( const Key& key ).

Iterators and indexes are in fact rather tangentially related concepts. An index alone does not allow you to access the container's data in any way, you must call a function from the container, like the subscript operator ([]) or find().

An iterator, however, can be "dereferenced" with * or -> even if you no longer have access to the original container. Sometimes iterators are passed around in C++ without their related container. They can also be incremented and/or decremented (depending on the container).


Many people use the terms "key" and "index" interchangeably, me included. This may not be entirely appropriate depending on the context, but they are generally an equivalent concept.

  • So an index is used to look up the data in the container, but cannot look up data in the container by itself? So what does an index do by itself? An iterator is a class but an index is? – Dog Jun 09 '16 at 16:33
  • @Dog An index can be anything (for some containers); but it isn't something with any connection to the container. Again with arrays: the index is an integer. So you can access an element of an array with `x` given `int x = 10;`, but `x` alone doesn't have any connection to the data; only `array[x]` does. Iterators carry their connection to the container with them. –  Jun 09 '16 at 16:35