1

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

        }
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Hani Honey
  • 2,101
  • 11
  • 48
  • 76

2 Answers2

2

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 1
    Indexes can also be invalidated (for example by clearing the vector), so the simple fact of being invalidated is not what makes iterators worse than indexes for this purpose. Importantly, indexes can later be checked for validity by comparing them against the vector size, which iterators can't. – Steve Jessop Mar 29 '14 at 17:46
  • That's a curious view of invalidation. – Deduplicator Mar 29 '14 at 17:48
  • I don't find it curious, but then it is my view so of course I wouldn't ;-) I don't think that 27 is a valid index in a vector of size 0. I do think it is a valid index in a vector of size 28. Hence if you change the size of the vector from 28 to 0 you invalidate the index. It's a somewhat different meaning from the iterator, since if an iterator is invalid for accessing the vector then it's useless for anything. A `size_t` can be invalid as an index in a particular vector, but of course would still be valid for use in arithmetic or in the comparison I mentioned. – Steve Jessop Mar 29 '14 at 17:50
0

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.

Community
  • 1
  • 1
user3159253
  • 16,836
  • 3
  • 30
  • 56