4

我的问题如下:我使用了一个迭代器,我想将每个元素与下一个元素进行比较。原型如下所示,如何增加迭代器才能进行比较?另外,我怎样才能为这种情况的发生设置适当的条件?我的意思是如何指向最后一个元素,而不是像 end() 函数一样指向最后一个元素:

std::vector<T>::const_iterator it;
std::vector<T>::const_iterator it2;
for (it = set.begin(), it != set.end(); it++)
{
  // some things happen
  if ( final == it )
  {
     if ( it != set.end()-1 ) // how to write properly condition?
     {
        it2 = it + 1; //how to assign the next here?
        if (...)//some condition
        {
          if ( it->func1() - it2->func1()) < 20 ) //actual comparison of two consecutive element values
            // do something
        }
      }
   }
}
4

5 回答 5

5

C++11中使用函数std::next()std::prev()

你的代码可能变成:

// before
it != std::set.end()-1

// after
it != std::prev(set.end())

// before
it2 = it + 1;

// after
it2 = std::next(it);

对于非矢量容器也是如此,例如 map、set 或其他。

注意:在 之后std::next(it),“it”迭代器保持不变!

注 2:it2 = std::next(it,n);根据需要使用来增加。

于 2016-01-27T11:11:51.637 回答
2

You can use adjacent_find to solve that. You should use the second form of that function (with predicate) and pass to the predicate your some things happen and some condition in c-tor

auto found = std::adjacent_find( set.begin(), set.end(),
    [some_comdition]( const T & left, const T & right ) {
        if ( some_comdition ) {
            if ( left.func1() - right.func1() < 20 ) {
                do_smth();
                // return true; if there's no need to continue
            }
        }
        return false;
    }
);
于 2013-02-12T12:58:11.747 回答
1

基于it++可接受的事实,我们应该定义一个名为 的新迭代器itplusone,它被初始化为itplusone = ++it。这样,您可以安全地使用指向下一项的迭代器的含义ititplusone同样清楚的是,以 terms 为界的迭代器的范围itplusone != set.end()。我使用这种方法来计算路径的总权重,该路径被定义为列表对象。

于 2014-10-04T09:22:08.027 回答
-1

In the for loop, you use it++ which means it = it + 1, which is perfectly ok. So this one will be fine also it2 = it + 1. it2 will be pointing to the next value.

In the for loop again, you use it != set.end(), which is again perfectly ok. So you can also it + 1 < set.end(), just like you did in your code.

I don't see anything wrong in your code, just wanted to explain.

于 2013-02-12T12:55:19.337 回答
-1

有点晚了,才发现它,但就像上面提到的, ++​​ 迭代器工作正常。

vector<string> P
auto itA = begin(P);

while(itA != end(P))
{
    if(itA != end(P))
    {   
        ++itA; // 
    } 
}
于 2020-12-08T04:58:00.180 回答