c++ - 将 const auto & 转换为迭代器

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

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

目前,我正在尝试在 for 循环中删除一个元素,在它被使用之后,想知道是否有任何方法可以转换 const auto &it : nodesstd::vector<txml::XMLElement*>::iterator

有问题的代码:

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

我很确定我可以重写 std::vector<txml2::XMLElement*>作为 const 指针,但不希望这样做,因为这段代码目前仅用于调试。

最佳答案

您不应尝试将基于范围的 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;
});

关于c++ - 将 const auto & 转换为迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557430/

相关文章:

c++ - 在 C++11 中使用 SFINAE 在具有相同签名的两个函数之间进行选择

c++ - 哪些编译器可以使用#include <thread> 或者换句话说,支持同样免费的 C++ 11?

python - 如何制作一个函数,一次返回一个列表中的项目?

c++ - 具有合成和继承属性的深度递归 qi 语法(解析器)

c++ - 长长除错

c++ - << operator override 使用 g++ 而不是 Windows 编译

C++:我可以使用成员变量的迭代器并使其成为类之一吗?

c++ - 让奴隶在MPI中互相等待

c# - C# 应用程序中的 C++ lib RTTI

java - Java中元素迭代器的并行计算