【问题标题】:Increment an iterator c++增加一个迭代器 c++
【发布时间】:2013-01-27 18:49:20
【问题描述】:

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

【问题讨论】:

  • 您试图用这些多个迭代器解决什么问题?
  • 我到现在只使用一个迭代器(这只是代码的一部分)。我希望能够比较集合中两个连续的 func1。所以我需要一个指向实际的迭代器,一个指向下一个的迭代器。有更好的方法吗?我可能在这里做了一些矫枉过正,请纠正我
  • 对于set.end()-1,使用set.rbegin()

标签: c++ iterator increment


【解决方案1】:

有点晚了,才发现,不过如上所述,++迭代器工作正常。

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

while(itA != end(P))
{
    if(itA != end(P))
    {   
        ++itA; // 
    } 
}

【讨论】:

    【解决方案2】:

    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); 可以根据需要增加。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        您可以使用adjacent_find 来解决这个问题。您应该使用该函数的第二种形式(带有谓词)并将您的 some things happensome condition 在 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;
            }
        );
        

        【讨论】:

          【解决方案5】:

          for 循环中,您使用it++ 表示it = it + 1,这完全可以。所以这个也可以it2 = it + 1it2 将指向下一个值。

          再次在for 循环中,您使用it != set.end(),这又完全没问题。所以你也可以it + 1 &lt; set.end(),就像你在代码中所做的那样。

          我看不出你的代码有什么问题,只是想解释一下。

          【讨论】:

          • std::vector 是这样,但一般来说,it++not 表示it = it + 1。所有迭代器都支持增量,但只有随机访问迭代器支持加法。
          • 我可能还想将它用于其他容器,所以这是我的问题,如何将下一个元素分配给我的新迭代器。我在上面用数字指出了这个问题的答案
          猜你喜欢
          • 2020-03-09
          • 2015-05-03
          • 1970-01-01
          • 1970-01-01
          • 2018-07-14
          • 2012-10-23
          • 2022-01-22
          • 1970-01-01
          • 2010-11-05
          相关资源
          最近更新 更多