我正在尝试在以下向量中插入字符串:std::vector<std::string> fileVec
。
fileVec
中已经包含许多元素(最多一百万个字符串),在我调用这些行之前:
int index = 5;
//there is some code here to find the index i want insert the text (let's take for example has value 5)
fileVec.insert(fileVec.begin() + index, "add this text");
我的问题是插入文本需要花费很多时间(特别是如果索引很小的时候。)>
有没有更快的方法可以在大向量中添加元素(不删除其他元素?
fileVec.insert
不会被调用很多次,大约15次。
我正在尝试在以下向量中插入字符串:std :: vector <:string>fileVec。在我调用这些行之前,fileVec中已经包含许多元素(最多一百万个字符串):int ...
[std::vector
]不是为频繁在中间添加元素而设计的,尤其是当它很大时(一百万个元素非常大。),请考虑使用std::list
-双链表,其中在中间添加元素的速度非常快,因为您要做的就是更改一些指针。在std::vector
中,所有元素都必须移动,这当然会导致大量开销。