Megamozg
Megamozg

Reputation: 1063

Empty iterator range in vector constructor

Is it valid to pass empty iterator range in vector constructor? I.e. would it be undefined behaviour in the following code?

std::set<int> empty_set;
std::vector<int> target_vector(empty_set.begin(), empty_set.end());

According to cppreference explanation, this constructor:

Constructs the container with the contents of the range [first, last).

Doest it mean first must be dereferenceable?

Upvotes: 7

Views: 684

Answers (2)

Toby Speight
Toby Speight

Reputation: 30827

It's perfectly legitimate to construct a std::vector from an empty range. If first==last, the new vector will have no elements, and first will not be dereferenced.

The code you have is well-defined, and does what you expect.


Since a pointer can be used as an iterator, this even means that this code is well-defined (and returns zero):

#include <vector>

int main()
{
    int const* const p = nullptr;
    std::vector<int> v(p, p);
    return v.size();
}

Upvotes: 10

Eduard Rostomyan
Eduard Rostomyan

Reputation: 6546

No, there is no such requirement.

What it does it allocated memory of size std::distance(first, last) then copies the containment in loop.

Upvotes: 2

Related Questions