c++ - How to initialize an iterator to something invalid if the container is not known? -


i want use visitor given more complex function should inflict changes on container via visitor of has general knowledge. example reduced minimum. real visitor has more functions , not handle container @ all.

class intersectionhandler{ public:     virtual void advance()=0;   virtual void treatintersection()=0; };  class overlapdisabler: public intersectionhandler{ private:   std::vector<segment>  mempty;   std::vector<segment>* mplinestosearch;   std::vector<segment>::iterator mlineiter;  public:   insidecollector():mempty(),mplinestosearch(&mempty),mlineiter(mempty.end(){}    void setlinecontainer(std::vector<segment>* lines){     mplinestosearch = lines;     mlineiter = mplinestosearch->begin();                                                               }    void advance(){     if(mlineiter != mplinestosearch->end()) ++mlineiter;   }   void treatintersection(){     if(mlineiter != mplinestosearch->end()) mlineiter->disable();   }     }; 

to intitailize iterator use dummy vector, must keep class member in case. initialise iterator globally invalid value such 0 pointer.

unfortunately 0 not valid value iterator many compilers , seems little odd use. there cleaner way accomplish trying without resorting empty dummy container?

the answer

you can't, there no value standard iterators puts them "invalid state".


proposed solution

instead of relying on value of mlineiter, default-initialize mlineiter , initialize mplinestosearch nullptr in constructor.

this way mlineiter isn't valid iterator if mplinestosearch still nullptr.


sample implementation

class overlapdisabler: public intersectionhandler{ private:   std::vector<segment>* mplinestosearch;   std::vector<segment>::iterator mlineiter;  public:   insidecollector() : mplinestosearch (nullptr), mlineiter() { }    ...    void advance(){     if (mplinestosearch == nullptr)       return; // no iterator increment      if(mlineiter != mplinestosearch->end()) ++mlineiter;   }   ...         void treatintersection(){     if(mplinestosearch == nullptr)       return; // iterator doesn't refer element      if(mlineiter != mplinestosearch->end()) mlineiter->disable();   }     }; 

( note: if compiling source c++03, nullptr isn't available; if case use null or 0 initialize pointer )


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -