【问题标题】:traverse std::list , holding 2 last values遍历 std::list ,保存 2 个最后的值
【发布时间】:2020-08-18 06:27:20
【问题描述】:

我需要遍历 std::list 持有 2 个最后一个值,即如果我的列表是 [1,2,3,4,5,6]

iteration1 : v1 = 1, v2 = 2
iteration2 : v1 = 2, v2 = 3
iteration3 : v1 = 3, v2 = 4
iteration4 : v1 = 4, v2 = 5
iteration5 : v1 = 5, v2 = 6

我试过

auto next = _contour.begin();
auto prev = next;

while( next != _contour.end())
{
    prev = next;
    next++;
}

但效果不好——遍历结束时出现问题。在最后一次迭代中,next 指向列表之外。

如何在每次迭代检查next 时以我不希望的良好性能正确执行此操作?

【问题讨论】:

  • 我认为代码是正确的。你确实检查了next!= _contour.end(),所以它不应该超过。
  • 我猜真正的工作是在next++ 行之后完成的,并且next 可以等于.end()。
  • 问题中的代码肯定不正确。无论 OP 将实际循环体放在哪里,它都不会做正确的事情。
  • 您不能不检查每次迭代,因为列表可能会在每次迭代时结束。您可以展开循环以增加一点性能,但您拥有的代码是标准的。

标签: c++ list


【解决方案1】:

正如您所暗示的,问题是您在增加它之前检查next != _contour.end() 是否,并且在增加它之后您不能确定它不等于结束迭代器。

要解决此问题,请切换循环中的逻辑,以便在每次迭代之前测试 next 的新值。

例如:

auto current = _contour.begin();
// Make sure the list isn't empty before we go charging ahead.
if (current != _contour.end()) {
    decltype(current) prev;

    while ((prev = current), (++current != _contour.end())) {
        std::cout << "v1:" << *prev << " v2:" << *current << std::endl;
    }
}

(Demo)

【讨论】:

  • 可能也可以将“当前”移动到if() 语句中
  • @Swift-FridayPie 不是没有多余的测试,除非我误解了你在说什么。据我所知,你不能在同一个条件表达式中声明一个变量并测试它的初始值。
  • 在 C++17 中,if (int i = 1; i != 0) {...}.
  • ^ 除了人们并不总是能读懂逗号和分号的“魔法”
  • @Evg 啊,我不知道这种新语法。我只想说我的答案是针对 C++11 或更高版本的。 (我不喜欢假设每个人都可以访问 C++17 实现。)
【解决方案2】:

您的循环应该交换增量和检查条件,以免超出范围。它可以通过多种方式完成,使用各种循环,例如

   auto  next = _contour.begin();
   auto prev = next;

   if( !_contour.empty())
     while( ++next != _contour.end())
     {
        //std::cout << *prev << ":" << *next << std::endl;
        prev = next;
     }

或单线for:

  if( !_contour.empty())
     for(auto next = _contour.begin(), prev = next; ++next != _contour.end(); prev = next )
     {    
         //std::cout << *prev << ":" << *next << std::endl;
     }

【讨论】:

  • 注意:如果列表为空,则调用未定义的行为。
猜你喜欢
  • 2021-10-18
  • 2013-08-11
  • 1970-01-01
  • 2018-01-22
  • 2022-01-18
  • 1970-01-01
  • 2012-01-09
  • 2020-11-07
相关资源
最近更新 更多