c++ 添加到std::vector的中间

xmakbtuz  于 2022-11-27  发布在  其他
关注(0)|答案(3)|浏览(254)

在C++中,有没有办法将值添加到vector的中间?假设我有:

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

我想把其中一个字符串分解,然后把所有的片段放回vector,我该怎么做呢?,分解的字符串可以在任何地方,index = 0,中间的某个地方,或者index = a.size() - 1

bvuwiixz

bvuwiixz1#

您可以在位置i处插入vector,方法是写入

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

然而,这不是很有效;它的运行时间与插入元素后的元素数成正比。如果您打算拆分字符串并将它们添加回去,那么最好使用std::list,它支持在任何地方进行O(1)插入和删除。

q3qa4bjr

q3qa4bjr2#

您可以这样做,但速度会很慢:

int split = 3; // where to split
a.insert(a.begin()+index, a[index].substr(0, split));
a[index+1] = a[index+1].substr(split);
au9on6nz

au9on6nz3#

在这个例子中动态地找到向量中间并插入新元素。

std::vector <std::string> friends;

friends.push_back("Ali");
friends.push_back("Kemal");
friends.push_back("Akin");
friends.push_back("Veli");
friends.push_back("Hakan");
    
// finding middle using size() / 2
int middleIndexRef = friends.size() / 2;

friends.insert(friends.begin() + middleIndexRef, "Bob");

相关问题