Reputation: 10284
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
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
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
Reputation: 36433
You want distance
http://www.cplusplus.com/reference/std/iterator/distance/
(*iter)->Index(distance(agents.begin(),iter));
Upvotes: 6