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

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.



Solution 1:[1]

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)

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika
Solution 2 Peter Mortensen