简体   繁体   中英

c++ list iterator arithmetic replacement ideas

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?

Since it's a list, random access is slow. Fortunately for you:

  1. you're always starting at the beginning, and
  2. std::list has a size() method

here'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
}

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) {

}

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 )
    {
        //...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM