Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty iterator range in vector constructor

Tags:

c++

stl

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?

like image 951
Megamozg Avatar asked Jun 06 '18 10:06

Megamozg


People also ask

How do you make a vector empty in C++?

clear() function is used to remove all the elements of the vector container, thus making it size 0.

Do I need to initialize a vector in C++?

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.

What is C++ vector iterator?

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.

How do I get the size of a vector in C++?

vector::size() size() function is used to return the size of the vector container or the number of elements in the vector container.


2 Answers

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();
}
like image 103
Toby Speight Avatar answered Sep 20 '22 13:09

Toby Speight


No, there is no such requirement.

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

like image 38
Eduard Rostomyan Avatar answered Sep 22 '22 13:09

Eduard Rostomyan