Obtaining the position of an element with a collection

  • Thread starter =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=
  • Start date
?

=?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=

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,
 
R

Robbie Hatley

Ney André de Mello Zunino said:
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,

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

Ioannis Vranos

Ney said:
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. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top