Archived

This topic is now archived and is closed to further replies.

gimp

How do I get the index of an iterator?

Recommended Posts

Shannon Barber    1681
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
null_pointer    289
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

Share this post


Link to post
Share on other sites