Question

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;
            }

        }
Était-ce utile?

La solution

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.

Autres conseils

Check the vector iterator invalidation rules e.g. 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top