Caching the end iterator - Good idea or Bad Idea?

前端 未结 8 1744
臣服心动
臣服心动 2021-02-04 03:36

Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:



        
8条回答
  •  别那么骄傲
    2021-02-04 04:21

    I often use this style for iterating containers:

    // typedef std::vector Persons;
    Persons::iterator it = persons.begin(), end = persons.end();
    for (; it != end; ++it)
    {
        Person & person = *it;
        // ...
    }
    

    Erasing an element from a vector invalidates all iterators after the erased position.

    I'm not certain about the other container types. In any case I think it would be safe to assume that all iterators become invalid after an erase. If you really need very specific information then you can always look it up. I rarely need this because because of my rather conservative coding style.

提交回复
热议问题