Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does vector know to reserve first when initializing by a pair of iterators?

Tags:

c++

stl

Consider the following code.

struct MyData{
    MyData(const BYTE* pData, size_t uSize) 
        : bucket_(pData, pData + uSize) 
    {}     
    std::vector<BYTE> bucket_;
};

Does my bucket_ do the reserve first when initializing from a pair of iterators? Something like vec.reserve(std::distance(begIter, endIter)).

Or it just simply perform a serious of push_back or back_inserter_iterator::operator= ?

If it does not, I may need to initialize it with uSize of 0 then do the memcpy_s in constructor block.

like image 228
Chen OT Avatar asked Feb 24 '17 08:02

Chen OT


2 Answers

Does my bucket_ do the reserve first when initializing from a pair of iterators?

Yes, it does in effect.

Standard draft:

Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order log(N) reallocations if they are just input iterators.

(Pointers are random access iterators)

like image 177
eerorika Avatar answered Oct 20 '22 01:10

eerorika


Yes, it's guaranteed that there will be no reallocations, because pointers are RandomAccessIterators. vector.cons/9

template <class InputIterator>
vector(InputIterator first, InputIterator last, const Allocator& = Allocator());

Effects: Constructs a vector equal to the range [first, last), using the specified allocator.

Complexity: Makes only N calls to the copy constructor of T (where N is the distance between first and last) and no reallocations if iterators first and last are of forward, bidirectional, or random access categories. It makes order N calls to the copy constructor of T and order log(N) reallocations if they are just input iterators.

like image 45
WhiZTiM Avatar answered Oct 20 '22 00:10

WhiZTiM