Search code examples
c++c++11iteratorconstantsauto

Converting const auto & to iterator


A number of posts I've read lately claim for(const auto &it : vec) is the same as using the longer iterator syntax for(std::vector<Type*>::const_iterator it = vec.begin(); it != vec.end(); it++). But, I came upon this post that says they're not the same.

Currently, I'm trying to erase an element in a for loop, after it is used, and wondering if there is any way to convert const auto &it : nodes to std::vector<txml::XMLElement*>::iterator?

Code in question:

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

I pretty sure I could just rewrite std::vector<txml2::XMLElement*> as a const pointer, but would prefer not to since this code is just for debugging in the moment.


Solution

  • You should not be attempting to convert the range declaration in your range based for loop to an iterator and then deleting it whilst iterating. Even adjusting iterators while iterating is dangerous, and you should instead rely on algorithms.

    You should use the Erase-remove idom.
    You can use it with remove_if.

    It would look something like:

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

    Currently in the technical specifications, is erase_if.
    This is a cleaner version of the same behaviour shown above:

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