在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,10}; a.reserve(a.size()+b.size()); a.insert(a.end(),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).
因此,有两种情况:
>可以确定新容量,因此您无需拨打预留>新的容量无法确定,因此保留呼叫应该是有用的.