How to check if the iterator is initialized?

前端 未结 11 1486
孤城傲影
孤城傲影 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条回答
  •  猫巷女王i
    2021-02-05 07:19

    Most iterators don't have any global special values in the same way that all pointers can be NULL. Typically, though, you'll be working with specific containers, and if you keep one iterator per container, then you can use end() as the sentinel value:

    std::list mylist;
    std::list::iterator it = mylist.end();
    
    /* do stuff */
    
    if (it == mylist.end()) { ... }
    

    I'm not sure if insertion/deletion invalidates the end() iterator, though, so if you're planning on modifying your container, maybe save a copy of the original end, too:

    std::list::iterator end = mylist.end(), it = end;
    
    if (it == end) { ... }
    

    Though again I'm actually not sure if it's well-defined to compare two invalid iterators (in the event that the two do get invalidated).

提交回复
热议问题