简体   繁体   中英

How do I save the value of a vector iterator?

I have a member variable that is a vector iterator. I'm trying to save it so that I can access it later (variable name = mIt). However, in this method, for example, once the method ends, the value gets erased. How do I persist this value?

for(vector<Card>::iterator it = mCards.begin(); it != mCards.end(); ++it)
        {
            Card& currentCard = *it;
            temp = it;
            int compareResult = currentCard.GetLastName().compare(card.GetLastName());
            if (compareResult <= 0)
            {
                mIt = it;
                mCards.insert(temp, card);  // instead of it?
                return;
            }

        }

If you need to save the iterator for any reason, iterators are the wrong tool, as they can be invalidated. Better use an index, or convert your iterator before saving to an index:

size_t n = it - mCards.begin();

Tranform back using:

auto it = mCards.begin()+n;

That works because vector<> uses random access iterators.

Check the vector iterator invalidation rules eg here Iterator invalidation rules . Generally if you don't check capacity of std::vector you shouldn't use a previously acquired iterator after insertion of an element because the whole underlying storage may be reallocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM