简体   繁体   English

如何保存向量迭代器的值?

[英]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). 我正在尝试保存它,以便以后可以访问(变量名= 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. 之所以vector<>是因为vector<>使用随机访问迭代器。

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. 通常,如果您不检查std :: vector的容量,则不应在插入元素后使用先前获取的迭代器,因为可能会重新分配整个基础存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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