c++ - std::vector::insert 是否按定义保留?

标签 c++ c++11 vector

std::vector 上调用 insert 成员函数时,是否会在“推回”新项之前保留?我的意思是标准是否保证了这一点?

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

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());

还是其他更好的方法?

最佳答案

关于函数的复杂度[link] :

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

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).

因此,有两种情况:

  • 新的容量是可以确定的,所以你不需要调用reserve
  • 无法确定新容量,因此调用 reserve 应该会有用。

关于c++ - std::vector::insert 是否按定义保留?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359169/

相关文章:

c++ - 使用指针时的注意事项?

c++ - 重新哈希由列表 vector 组成的哈希表 C++

C++ WinApi Fillrect() 崩溃(多个矩形)

c++ - QPrintDialog 在窗口中显示两次

c++ - 从 'A&'类型的右值无效初始化 'A'类型的非const引用

c++ - 调用模板参数 constexpr 方法?

c++ - 绑定(bind)到引用丢弃限定符时出错

C++ - vector push_back() 在 fgets() 之后不工作

C++ 帮助学生的指针

c++ - header 中定义的函数是否保证内联?