How to check if the iterator is initialized?

前端 未结 11 1341
孤城傲影
孤城傲影 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:34

    Since there is no default value for iterators (like there is NULL for pointers), in situation where i need a common default value for a Object::iterator (before any actual Object has been created) I create a dummy static variable and use its ::end() as the default.

    Update : This only works for Release, because in DEBUG (or with _HAS_ITERATOR_DEBUGGING=1) comparison operators check if both iterators point to the same object/container.

    For example for vector I would do :

    class A
    {
    public :
        A() :  myIterator1(dummyVector.end()), myIterator2(dummyVector.end()) {}
        // needed iterators
        vector::iterator myIterator1;
        vector::iterator myIterator2;
    
        static const vector dummyVector;
    }
    
    #define  IT_NULL A::dummyObject.end()
    
    void maint() {
        A::dummyObject = vector(); // initialize the Null iterator
    
        A a;
        if(a.myIterator1 == IT_NULL) cout << "Iterator not yet initialized";
    }
    

提交回复
热议问题