【问题标题】:Converting const auto & to iterator将 const auto & 转换为迭代器
【发布时间】:2016-05-31 23:58:49
【问题描述】:

我最近阅读的一些帖子声称for(const auto &it : vec) 与使用更长的迭代器语法for(std::vector<Type*>::const_iterator it = vec.begin(); it != vec.end(); it++) 相同。但是,我发现this post 说它们不一样。

目前,我正在尝试擦除 for 循环中的元素,在使用后,想知道是否有任何方法可以将 const auto &it : nodes 转换为 std::vector<txml::XMLElement*>::iterator

有问题的代码:

std::vector<txml2::XMLElement *> nodes;
//...
for (const auto &it : nodes)
{
    //...       
   nodes.erase(it);
}

我很确定我可以将 std::vector&lt;txml2::XMLElement*&gt; 重写为 const 指针,但我不希望这样做,因为这段代码目前只是用于调试。

【问题讨论】:

    标签: c++ c++11 iterator constants auto


    【解决方案1】:

    您不应尝试将基于范围的 for 循环中的范围声明转换为迭代器,然后在迭代时将其删除。即使在迭代时调整迭代器也是危险的,你应该依赖算法。

    您应该使用Erase-remove idom
    您可以将其与remove_if 一起使用。

    它看起来像:

      nodes.erase( std::remove_if(nodes.begin(), nodes.end(), [](auto it){
    
        //decide if the element should be deleted
        return true || false;
    
      }), nodes.end() );
    

    目前在技术规范中,是erase_if
    这是上面显示的相同行为的更简洁版本:

    std::erase_if(nodes,[](auto it){
    
        //decide if the element should be deleted
        return true || false;
    });
    

    【讨论】:

    • 谢谢,帮助很大。最终只使用了set_difference,但这让我走上了正确的道路。
    【解决方案2】:

    你得到的不是迭代器而是对元素的引用。除非你想用它做一个std::find,否则很难从中得到一个迭代器。

    向量很好,因此您可以为每个元素增加一个计数器并执行nodes.begin() + counter 来获取迭代器,但这有点不合时宜。

    在for循环中删除迭代器也会导致你在向量结束后进行迭代,你可以测试这段代码:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main() {
        vector<int> v = {0,1,2,3,4,5,6};
    
        for (int x : v) {
            cout << x << endl;
    
            if (x == 2) {
                v.erase(v.begin() + 2);
            }
        }
        return 0;
    }
    

    如果你想使用迭代器,只需用它们循环,如果你想删除一个中间循环,你必须关注this answer

    for (auto it = res.begin() ; it != res.end(); ) {
      const auto &value = *it;
    
      if (condition) {
        it = res.erase(it);
      } else {
        ++it;
      }
    }
    

    请注意,您不需要指定迭代器的整个类型,auto 也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-04
      • 2012-06-07
      • 2011-09-02
      • 2014-02-21
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2016-12-14
      相关资源
      最近更新 更多