【问题标题】:Iterate up to and including position迭代到并包括位置
【发布时间】:2016-12-02 15:10:12
【问题描述】:

可能非常简单,但我无法理解它的atm

我有这个

// standard std::map and std::map::iterator
auto pos = map.find(val);
for(auto it = map.begin; it != pos; ++it)

我想搜索一个元素,然后处理之前的所有元素(容器是有序的,所以只是按迭代顺序)并包括查找位置,但这似乎不会检查位置“pos”处的最终元素。我怎样才能做到这一点?

【问题讨论】:

  • 如果您使用do-while 循环,则在循环体之后而不是之前检查条件。
  • if(pos != map.end()) //process pos here ?
  • map.begin() 不要忘记 ()
  • 不应该是for(auto it = map.begin(); it != pos; ++it)另外没有检查返回的it是否不等于map.end()

标签: c++ stl iterator


【解决方案1】:

只是移动东西。

auto pos = map.find(val);
for(auto it = map.begin(); it != map.end(); ++it)
{
    // Do something

    if (it == pos)
       break;
}

如果地图中可能不存在该值,这将简单地结束整个地图的迭代,这就是为什么明确需要it != map.end(); 来赶上这辆特殊的失控火车...

注意:如果您在 for 循环内有明确的 continues,则需要一些额外的 TLC。

【讨论】:

    【解决方案2】:

    您需要区分在map 中找到val 的情况与其他情况:

    void f(/*map::[const_]iterator*/ it);
    
    auto pos = map.find(val);
    for (auto it = map.begin(); it != pos; ++it)
        f(it);
    if (pos != map.end())
        f(pos);
    

    您可以使用do...while() 循环,但每次都必须检查pos!=end()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-28
      • 2011-05-12
      • 1970-01-01
      • 2013-10-20
      • 2021-11-12
      • 1970-01-01
      • 2013-12-24
      • 1970-01-01
      相关资源
      最近更新 更多