By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,435 Members | 2,033 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,435 IT Pros & Developers. It's quick & easy.

Obtaining the position of an element with a collection

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"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.


Jul 22 '05 #2

P: n/a
Ney André de Mello Zunino wrote:
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.

For containers with random iterators you can subtract the iterators,
which is what std::distance implementation for random iterators will
probably do too.
So the answer is, your approach sounds OK. :-)

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.