std :: vector :: insert是否按定义保留? [英] Does std::vector::insert reserve by definition?

查看:91
本文介绍了std :: vector :: insert是否按定义保留?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: vector 上调用 insert 成员函数时,它会吗?保留,然后推回新项目?我的意思是标准是否可以保证?

When calling the insert member function on a std::vector, will it reserve before "pushing back" the new items? I mean does the standard guarantee that or not?

换句话说,我应该这样做吗?

In other words, should I do it like this:

std::vector<int> a{1,2,3,4,5};
std::vector<int> b{6,7,8,9,10};
a.insert(a.end(),b.begin(),b.end());

或类似这样:

std::vector<int> a{1,2,3,4,5};
std::vector<int> b{6,7,8,9,10};
a.reserve(a.size()+b.size());
a.insert(a.end(),b.begin(),b.end());

还是其他更好的方法?

推荐答案

关于功能的复杂性 [链接]


插入的元素数量(复制/移动构造)
加上位置后的元素数量(

Linear on the number of elements inserted (copy/move construction) plus the number of elements after position (moving).

此外,如果范围插入(3)中的InputIterator至少不等于正向迭代器类别的
(即,只是一个输入迭代器)新的
容量无法事先确定,并且插入会导致
的大小(重新分配)增加对数复杂度。

Additionally, if InputIterator in the range insert (3) is not at least of a forward iterator category (i.e., just an input iterator) the new capacity cannot be determined beforehand and the insertion incurs in additional logarithmic complexity in size (reallocations).

因此,有两种情况:


  • 可以确定新的容量,因此您无需致电储备金
  • >
  • 无法确定新的容量,因此调用储备应该很有用。
  • The new capacity can be determined, therefore you won't need to call reserve
  • The new capacity can't be determined, hence a call to reserve should be useful.

这篇关于std :: vector :: insert是否按定义保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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