Dollarslice
Dollarslice

Reputation: 10284

indexing with iterators

Is there a way that I can get the count number for an iterator?

so if at first I had this:

for (int i = 0; iter < agents.size(); ++i)
{
    agents[i]->Index(i);
}

bearing in mind that Index() sets an integer, how would I do this with iterators?

for (std::vector<Agent*>::iterator iter = agents.begin(); iter < agents.end(); ++iter)
{
    (*iter)->Index(????)
}

Upvotes: 1

Views: 148

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477040

Most generally, you can always hack up something yourself:

{
    int i = 0;
    for (auto it = agents.begin(), end = agents.end(); it != end; ++it, ++i)
    {
         (*it)->set_int(i);
    }
}

If you have random access iterators, you can indeed use std::distance(agents.begin(), it) safely, as has been said already.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258608

You can substract iterators:

int distance = iter - agents.begin();

EDIT:

Only works for random access iterators. (+1 internet to Let_Me_Be)

Upvotes: 2

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36433

You want distance http://www.cplusplus.com/reference/std/iterator/distance/

(*iter)->Index(distance(agents.begin(),iter));

Upvotes: 6

Related Questions