gpt4 book ai didi

c++ - 调整 vector 大小后,为什么我不能增加 vector

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:05 25 4
gpt4 key购买 nike

我正在尝试使用 vector 编写一个可以循环的数据结构,类似于循环列表。我调整了我认为应该用十个元素初始化底层数组的大小。我不明白为什么我不能推进迭代器。有人可以帮忙吗。

我不能使用 push_back(),因为它总是会附加到末尾,这不是我想要的。

// re-use start of vector when get to end
#include <vector>
#include <iostream>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

class printme {
public:
void operator() (int val) {cout << val << endl; }
};


//get a debug assertion - message says: vector iterators incompatible
//I assume this means that it is invalid after previous it++
int main(int argc, char* argv[])
{
vector<int> myvec;
myvec.resize(10); //underlying array now has size=10 elements
vector<int>::iterator it = myvec.begin(); //point to start of array
for(int i = 0; i < 100; ++i) {
if(it == myvec.end()) //on 2nd iteration crashes here - invalid iterator
it = myvec.begin();

myvec.insert(it++, i);
}

//print contents of vector - check 90-99 printed
for_each(myvec.begin(), myvec.end(), printme());

return 0;
}

编辑将循环更改为此:

for(int i = 0; i < 100; ++i) {
if(it == myvec.end())
it = myvec.begin();

*it++ = i;
}

我没有正确理解插入。

最佳答案

根据您对输出的期望 - 我相信您误解了什么 insert是在做。以这种方式实现你的循环(不插入 - 只是替换)。 std::vector<>::insert将 vector 的大小增加一 - 我相信这不是您所期望的。

不要这样做:

myvec.insert(it++, i);

但是这个:

 *it++ = i;

然后你会得到你想要的输出:

   //print contents of vector - check 90-99 printed
for_each(myvec.begin(), myvec.end(), printme());

关于c++ - 调整 vector 大小后,为什么我不能增加 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12913347/

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