简体   繁体   English

c ++列表迭代器算术替换思想

[英]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. 在某些情况下,我需要从列表开始循环到(end-n)元素以及访问整个列表的其他元素。 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. 为我使用rbegin不是一个选项,因为我想从列表的开头得到匹配的第一个实例。

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 std::list有一个size()方法

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 你可以使用反向迭代器和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 )
    {
        //...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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