Sign in to follow this  

stl iterator position

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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]

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this