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?
clear() function is used to remove all the elements of the vector container, thus making it size 0.
Initializing a Vector in C++ The vector in C++ stores the reference of the objects and not the data directly. These objects can be of any data type like integer, char, string, etc. Unlike static containers like an array, a vector does not need a size to be initialized with.
Vector's iterators are random access iterators which means they look and feel like plain pointers. You can access the nth element by adding n to the iterator returned from the container's begin() method, or you can use operator [] . std::vector<int> vec(10); std::vector<int>::iterator it = vec.
vector::size() size() function is used to return the size of the vector container or the number of elements in the vector container.
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();
}
No, there is no such requirement.
What it does it allocated memory of size std::distance(first, last) then copies the containment in loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With