How do I get the index of an iterator?

Started by
4 comments, last by gimp 22 years, 4 months ago
I have an std::vector. I do a std::find to locate a certain element. But, I want to know the index of the element. Anyone know how I can find this out? Many thanks Chris Brodie http:\\fourth.flipcode.com
Chris Brodie
Advertisement
int index = it - &m_vMyvector[0];

I just did this earlier today - parallel arrays/vectors?

Magmai Kai Holmlor

"Oh, like you've never written buggy code" - Lee

"What I see is a system that _could do anything - but currently does nothing !" - Anonymous CEO

Edited by - Magmai Kai Holmlor on December 18, 2001 1:27:46 AM
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Thanks!

Yep parallel arrays. In this case it''s the object array and the names array in my resource manager. I do a lookup of the name then return the handle to the object in the other array.

Chris Brodie
http:\\fourth.flipcode.com
Chris Brodie
quote:Original post by Magmai Kai Holmlor
int index = it - &m_vMyvector[0];

I think in this case it''s actually safe to use m_vMyvector.begin () instead of &m_vMyvector[0], since they''re random iterators and the - should be overloaded properly (e.g. doesn''t depend on the iterator beign a pointer). But I understand your intention. =)

If you don''t have random iterators, there''s always the std::distance function (actually I think it''s a member of iterator; at my GF''s computer so I don''t have a reference on me.) So, for example, if you had an iterator in a list, and wanted to create a copy of the list with an iterator at the same position in the copy, you would use distance on the old list and advance on the new one.
Out of interest, why not use std::vector<std::pair<Name, Object> > or std::map<Name, Object> ?
Probably because of speed; viz. they do lookups much less often than random access. If you did std::vector< std::pair<> > then on each pass through a loop you would have to access it through a std::pair object...would MSVC be able to optimize that out?

Just a thought:

This is one reason why I think that a dynamic compiler would do very well with C++. The interface of std::map just fits the problem exactly, but with the wrong implementation inefficiency would make it unusable. Although the abstractions used by the standard library classes are excellent, if you want the most efficiency then you must choose the algorithms based on the characteristics of the data.

Use of the standard library classes could be specially watched by such a compiler, and it could adjust the algorithms used within them for each frequently accessed specialization according to the specifics of how it is accessed and so forth.

The standard library does not have to exist as a set of header files, you know.

- null_pointer

This topic is closed to new replies.

Advertisement