C ++ - 矢量迭代器不可递增的错误 [英] C++ - Vector iterator not incrementable error

查看:126
本文介绍了C ++ - 矢量迭代器不可递增的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have myVector with some values of the type Texture_Map which is just an int.

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

I'm not erasing anything... I just want to insert a value in each even iteration.

类似的东西:
如果我有这个向量 [1,2,3,4,5]

我的 Texture_Map :: TEXTURE_FLIP 99 ,那么我的最终向量应为:

And my Texture_Map::TEXTURE_FLIP is 99, then my final vector should be:

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

在第一个 insert()之后,我得到向量迭代器不可递增的问题错误。

After the first insert() I get the "Vector iterator not incrementable problem" error.

代码:

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

谢谢!

推荐答案

作为使用 <的结果的一部分向量上的code>插入 是:

As part of the consequence of using insert on a vector is that it:


如果是,则会导致重新分配new size()大于旧容量()。如果new size()大于capacity(),则所有迭代器和引用都将失效。否则,只有插入点之前的迭代器和引用仍然有效。过去的迭代器也是无效的。

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 返回迭代器的事实:

The issue you're seeing is that you're attempting to increment an iterator which is no longer valid - it's past the insertion point, so it's invalidated. The solution here is to take advantage of that fact that insert returns an iterator:

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

具体来说:


返回值

1-2)指向插入值的迭代器

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 ++ - 矢量迭代器不可递增的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆