Reputation: 723
I have a list that gets accessed in multiple places. There are some cases where I need to loop through the list from beginning to (end-n) elements and others where the whole list is accessed. I'm having trouble with the iterator arithmetic.
I want something that could do the following:
int n =10;
for (list<Term>::iterator itr = final.begin(); itr != (final.end()-n); itr++) {
//
}
does the following pseudo code make sense?
int N = myList.size() - n;
for (list<Term>::iterator itr = final.begin(),int length_reached=0; itr != (final.end() && length_reached<N; itr++,length_reached++) {
//
}
Using rbegin for me is not an option since I want the first instance of a match from the start of the list.
is there a better way of implementation here?
Upvotes: 1
Views: 80
Reputation: 1255
you can use reverse iterator and the std::advance
auto rit =final.rbegin();
std::advance(rit, n);
for (auto itr=final.begin(); itr!=rti.base(); ++itr) {
}
Upvotes: 0
Reputation: 311078
Yes you can do this way
if ( n < final.size() )
{
auto m = final.size() - n;
for ( auto first = final.begin(); m != 0; ++first, --m )
{
//...
}
}
If the iterator itself can be changed in the loop then you can write the loop condition the following way
if ( n < final.size() )
{
auto m = final.size() - n;
for ( auto first = final.begin(); m != 0 && first != final.end(); ++first, --m )
{
//...
}
}
Upvotes: 0
Reputation: 69902
Since it's a list, random access is slow. Fortunately for you:
std::list
has a size() methodhere's one way:
list<Term>::iterator itr = final.begin();
int to_do = std::max(0, int(final.size()) - n);
for ( ; to_do ; --to_do, ++itr )
{
// code here
}
Upvotes: 3