在 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/