添加到std :: vector的中间 [英] Adding to middle of std::vector

查看:321
本文介绍了添加到std :: vector的中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在C ++中的向量中添加值?说我有:

Is there a way to add values to the middle of a vector in C++? Say I have:

vector <string> a;
// a gets filled up with "abcd", "wertyu", "dvcea", "eafdefef", "aeefr", etc

,我想分解其中一个字符串,并将所有的部分放回向量。我该怎么做?我断裂的字符串可以是任何地方,索引= 0,中间某处,或索引= a.size() - 1

and I want to break up one of the strings and put all of the pieces back into the vector. How would I do that? the strings I break can be anywhere, index = 0, somewhere in the middle, or index = a.size() - 1.

推荐答案

您可以插入位置 i 的向量 >通过写

You can insert into a vector at position i by writing

v.insert(v.begin() + i, valueToInsert);

然而,这不是很有效率;它在与在元素被插入之后的元素的数量成比例的时间中运行。如果你打算拆分字符串并添加它们,你最好使用 std :: list ,它支持O(1)插入和删除无处不在。

However, this isn't very efficient; it runs in time proportional to the number of elements after the element being inserted. If you're planning on splitting up the strings and adding them back in, you are much better off using a std::list, which supports O(1) insertion and deletion everywhere.

这篇关于添加到std :: vector的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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