gpt4 book ai didi

C++ - vector 迭代器不可递增错误

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:14 25 4
gpt4 key购买 nike

我的 myVector 有一些 Texture_Map 类型的值,它只是一个 int

我没有删除任何东西...我只想在每个偶数迭代中插入一个值。

类似于:如果我有这个 vector [1,2,3,4,5]

而我的 Texture_Map::TEXTURE_FLIP99,那么我的最终 vector 应该是:

[99,1,99,2,99,3,99,4,99,5]

在第一个 insert() 之后,我得到了“Vector iterator not incrementable problem”错误。

代码:

myVector.push_back(Texture_Map::TEXTURE_INIT);

for(unsigned int i = 0 ; i < m_max_pieces-2; i++)
myVector.push_back((Texture_Map::TextureID)i);

std::random_shuffle(myVector.begin(), myVector.end());

std::vector<Texture_Map::TextureID>::iterator it = myVector.begin();

for (it=myVector.begin(); it<myVector.end(); it++)
{
myVector.insert(it,Texture_Map::TEXTURE_FLIP);
}

谢谢!

最佳答案

作为使用 insert 的结果的一部分在 vector 上是它:

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

您看到的问题是您试图增加一个不再有效的迭代器 - 它已经超过了插入点,因此它已失效。这里的解决方案是利用 insert 返回一个 iterator 的事实:

iterator insert( iterator pos, const T& value );

具体来说:

Return value
1-2) Iterator pointing to the inserted value

所以你想要:

for (it=myVector.begin(); it<myVector.end(); it++) {
// now it will point to TEXTURE_FLIP
it = myVector.insert(it,Texture_Map::TEXTURE_FLIP);

// now it will point back to the original element
++it;
}

关于C++ - vector 迭代器不可递增错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com