"Ney André de Mello Zunino" <zu****@inf.ufsc.br> wrote in message news:2u*************@uni-berlin.de...
Hello.
To find the position of an element within a collection, I currently
follow these two steps:
1. obtain an iterator to the element (i.e. find it)
2. use std::distance with coll.begin() and the previous iterator
This works, but I still would like to know if there is a better way
which I might be overlooking.
Thank you,
--
Ney André de Mello Zunino
It depends on what kind of "collection". With vectors and deques, the
index is the postion. With maps, "position" is not a very useful concept
because lookup is done (behind the scenes) using b-tree technology.
With lists, there is no index and no random iterators, so the fastest
way to find effective "index" or "position number" would be a linear
search:
list<std::string> Blat;
// (put stuff into list here)
list<std::string>::iterator Bob, Jack;
Bob = Blat.find("Vanilla");
int i=0;
for (Jack = Blat.begin(); Jack != Bob ; ++Jack)
{
++i;
}
The value of i will now be the effective "index" of the first occurence
of "Vanilla" in your list.