繁体   English   中英

通过每次重新调整向量的大小在向量中插入元素是否会花费更多时间?

[英]Does inserting an element in vector by re-sizing the vector every time takes more time?

我在这里遇到决策问题。 在我的应用程序中,我需要合并两个向量。 由于数据顺序很重要(因此不应排序),因此我无法使用stl算法。

  • 两个向量都包含有时相同的数据,或者在最坏的情况下可能有75%的差异。

  • 目前,我对两种方法感到困惑,

     Approach 1: a. take an element in the smaller vector. b. compare it with the elements in bigger one. c. If element matches then skip it (I don't want duplicates). d. If element is not found in bigger one, calculate proper position to insert. e. re-size the bigger one to insert the element (multiple time re-size may happen). Approach 2: a. Iterate through vectors to find matched element positions. b. Resize the bigger one at a go by calculating total size required. c. Take smaller vector and go to elements which are not-matched. d. Insert the element in appropriate position. 

请帮助我选择合适的一个。 并且,如果有比矢量更好的方法或更简单的技术(如stl算法)或更简单的容器,请在此处发布。 谢谢。

您不应该专注于调整大小。 在方法1中,应该使用vector.insert(),因此实际上不需要自己调整向量的大小。 这可能会导致基础缓冲区的重新分配自动发生,但是必须谨慎地实现std :: vector,以使这些操作的总成本很小。

算法的真正问题是插入,可能还有搜索(您没有详细介绍)。 当您将向量插入到除结尾处之外的任何位置时,插入点之后的所有元素都必须在内存中上移,这可能会非常昂贵。

如果希望此速度很快,则应通过一次附加一个元素,并且不在中间插入两个元素,从两个输入向量构建一个新向量。

看起来您可以用比O(n.log(n))更好的时间复杂度来完成此操作,因为从法线向量中删除重复项会花费n.log(n)的时间。 因此,使用set删除重复项可能是您最好的方法。 n这里是两个向量中元素的数量。

根据您的实际设置(例如,如果要向矢量添加对象指针,而不是将值复制到一个指针中),使用std :: list可能会获得明显更快的结果。 std :: list允许固定时间插入,这将是巨大的性能开销。

插入可能有点尴尬,但是完全可以做到的,只需更改几个指针(便宜),而不是通过向量插入即可,该向量将每个元素移开以放置新元素。

如果它们最终需要作为矢量,则可以将列表转换为带有(unested)之类的矢量

std::list<thing> things;

//efficiently combine the vectors into a list
//since list is MUCH better for inserts
//but we still need it as a vector anyway

std::vector<thing> things_vec;
things_vec.reserve(things.size()); //allocate memory

//now move them into the vector
things_vec.insert(
    things_vec.begin(), 
    std::make_move_iterator(things.begin()), 
    std::make_move_iterator(things.end())
);

//things_vec now has the same content and order as the list with very little overhead

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM