stl iterator position

This topic is 4755 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi If I'm iteratind through a vector with this: for(iter = day_close.end();iter !=day_close.begin(); iter--) { } whats the best way to get the position it is in the vector? cheers

Share on other sites
Either keep track of it yourself, or rely on the fact that the vector's has fast array indexing, or that it's got a continous memory block by using pointer subtraction).
iter = vector.end();for(size_t i = vector.size(); i; --i) { // do stuff.. --iter;}
Trying to process an element beyond the end of the vector first was intentional, right?

And if you're satisifed with a solution that only works with vectors and raw arrays then you might try this instead.
for(;;) { size_t i = iter - vector.begin();}

Share on other sites
C++ provides a function called std::distance for this very purpose.

Its in the <iterator> header file, and takes two iterators, you would pass in the begin() and current iterator.

Share on other sites
doynax brought up processing day_close.end(), which doesn't point to anything in day_close. That is almost certainly a bug. If you need to iterate through the list in reverse order you would use the reverse_iterator (it seems kinda of odd at first, but it make sense when you realise that you can use it in the stl alogorithms and what not).

For example
#include <iostream>#include <vector>using namespace std;int main(int argc, char *argv[]){    vector<int> test;    test.push_back(1);    test.push_back(2);    test.push_back(3);        vector<int>::reverse_iterator iter;      for(iter = test.rbegin();iter !=test.rend(); iter++){ //yes it's ++       cout << *iter;    }    cout << endl;        char junk;    cin.get(junk);}

If you need to know the position, accessing the vector with operator[] instead of iterators maybe better suited for what your doing.

[Edited by - Cocalus on May 14, 2005 10:36:49 PM]

• 10
• 18
• 14
• 19
• 15