I am confused...

K

Kitty

Is it possible to know the relative position of a given element, say x, in
the container? Assume x is unique.

For example,

vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);

Then the position of element 50 relative to 20 is +3. Actually, how to find
this relative position? Thanks.
 
A

alexmdac

Yes it is! Well it is for a sequence container such as a list or a
vector. Use std::find to get iterators to both the elements. Then use
std::distance to get the distance between them.
 
D

David Harmon

On Tue, 7 Dec 2004 19:54:38 +0800 in comp.lang.c++, "Kitty" <No
spam> wrote,
How about using "-" to calculate the distance?
Thanks.

OK for vector::iterator or other random access iterator types.
Will fail for more complicated iterator types where std::distance
still does the right thing.
 

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

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,978
Members
47,561
Latest member
gjsign

Latest Threads

Top