我最近读过的许多帖子声称 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<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/