Find the position of an elemant in a vector

S

Sunil Varma

Hi,

I've to write a function similar to this.

int process(const vector<int>& vct,int key)
{
// Here I've to find the position of key in the vector and do some
processing.
}

Is there any fucntion in algorithm which directly gives the position of
an elemant.

find() returns an iterator but not the postion of the elemant.
Is there any function equivalent to indexof()?

Regards,
Sunil
 
M

mlimber

Sunil said:
Hi,

I've to write a function similar to this.

int process(const vector<int>& vct,int key)
{
// Here I've to find the position of key in the vector and do some
processing.
}

Is there any fucntion in algorithm which directly gives the position of
an elemant.

find() returns an iterator but not the postion of the elemant.
Is there any function equivalent to indexof()?

Use the result of find() - vct.begin().

Cheers! --M
 
I

IndyStef

There is a more 'official' method:

the 'distance' function is guaranteed to work, whereas the subtraction
is not. Especially when you swap your vector with a list at some
point, the subtraction will give you a compiler error, whereas
'distance' will give you the right answer. The subtraction can only
work on random access iterators.
For vectors, however, the subtraction is fine and works.

Stefan
 
E

eriwik

Not quite, more of a pointer to the element, not it's position. It does
not tell you anything about where in a container (of any type) the
element is. It's not much of a differance but think of it like this:
take the first element of a list and take an iterator to it, the insert
a new element at the beginning of the list, the iterator still points
to the original element even though it has changed position in the
list.
 

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
474,438
Messages
2,571,699
Members
48,796
Latest member
Greg L.
Top