Reputation: 1063
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
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
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