c++插入向量的已知位置
我希望在已知位置插入 C++ 向量。我知道 C++ 库有一个 insert() 函数,它接受一个位置和要插入的对象,但位置类型是一个迭代器。我希望使用特定索引插入向量,就像插入数组一样。
I wish to insert into a c++ vector at a known position. I know the c++ library has an insert() function that takes a position and the object to insert but the position type is an iterator. I wish to insert into the vector like I would insert into an array, using a specific index.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该做你想做的。
请注意,当向量重新分配时,迭代器可能会失效。请参阅此网站。
编辑:我不确定为什么另一个答案消失了......但另一个人提到了一些类似的内容:如果我没记错的话,这应该没问题。This should do what you want.
Please be aware that iterators may get invalidated when vector get reallocated. Please see this site.
EDIT: I'm not sure why the other answer disappeared...but another person mentioned something along the lines of:If I remember correctly, this should be just fine.把这些事情总结起来总是好的:
应该可以了。有一个现已删除的答案,您可以从索引构造迭代器,但我以前从未见过。如果这是真的,那绝对是正确的选择;我现在正在找。
It's always nice to wrap these things up:
That should do it. There is a now deleted answer that you can construct an iterator from an index, but I've never see that before. If that's true, that's definitely the way to go; I'm looking for it now.
查看调试跟踪。最后执行的是 std::copy(__first=0x90c6fa8, __last=0x90c63bc, __result=0x90c6878)。回顾一下导致它的原因,您调用了 insert,给出了插入位置 0x90c63bc。 std::copy 将范围 [first, last) 复制到结果,该结果必须有空间容纳最后一个 - 第一个元素。该调用最后一个<首先,这是非法的(!),所以我猜测您给出的插入位置是错误的。你确定 vnum 没有在某处下溢吗?在显示该跟踪的 GDB 中,您应该运行
进行检查。事实上,如果你不只是缩写你的问题,我就发现了你的错误。你的第二行是:
它应该是:
第一行给出了相对于一些称为顶点的其他变量的开头的插入点,而不是你想要插入的变量。
Look at that debugging trace. The last thing that's executed is std::copy(__first=0x90c6fa8, __last=0x90c63bc, __result=0x90c6878). Looking back at what caused it, you called insert giving the position to insert at as 0x90c63bc. std::copy copies the range [first, last) to result, which must have room for last - first elements. This call has last < first, which is illegal (!), so I'm guessing that the position you're giving to insert at is wrong. Are you sure vnum hasn't underflowed somewhere along the line? In GDB with that trace showing, you should run
to check. In fact, if you haven't just abbreviated in your question, I've just found your bug. Your second line is:
It should have been:
The first line gives the insertion point relative to the start of some other variable called vertices, not the one you want to insert into.