Domanda

I was trying to clarify my concept on iterators and while reading on Random Access Iterators the book states that these iterators can be used with indexes for instances iterat[myIndex]. Now I have used Random Access iterators with vectors in a trivial manner as such:

std::vector<int>::iterator it;

for(it = vec.begin() ; it != vec.end() ; it++)
{
 std::cout << *it
}

I wanted to know how I would use an index with a Random Access iterator and when would I need to ? Any suggestions would be appreciated

È stato utile?

Soluzione

Assume you need to look at the predecesdor and the successor of a position (assuming they are there). You could use

it[-1] // predecessor
it[0]  // current position same as *it
it[1]  // successor

Of course, when present you can also use other indices. Although the subscript operator needs to be defined I don't think I ever needed it in an algorithm. The positioning operations are a lotmore important.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top