How to check if the iterator is initialized?

前端 未结 11 1365
孤城傲影
孤城傲影 2021-02-05 06:30

If I use a default constructor for an iterator, how to check if it was assigned later on?

For pointers, I could do this :

int *p = NULL;
/// some code
         


        
11条回答
  •  情歌与酒
    2021-02-05 07:11

    As far as I know you must always initialize your iterators and the easiest way is to make them equal to 'container'.end() In certain cases it looks like working, we had some problems with code that worked with VC6 and stopped working with VC2010. Look at this example compiled with g++ where it works for the vector but not for the map:

    # Test iterator init, compile with: g++ test-iterator.cpp -o test-iterator
    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector vec;
        std::vector::iterator it;
    
        if (it != vec.end())
        {
                std::cout << "vector inside!" << std::endl;
        }
        else
        {
                std::cout << "vector outside!" << std::endl;
        }
    
        std::map mp;
        std::map::iterator itMap;
    
        if (itMap != mp.end())
        {
                std::cout << "map inside!" << std::endl;
        }
        else
        {
                std::cout << "map outside!" << std::endl;
        }
    
        return 0;
    }
    

提交回复
热议问题