Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the official behavior for std::vector range constructor when the first itr comes after the last?

Assuming you have a valid starting point:

std::vector<UINT32> host = {1,2,3,4,5};

When you try to construct another vector using iterators:

std::vector<UINT32> client(host.begin(),host.end());

// client.size() is 5. Elements begin -> end look just like host.

But what happens if the iterators are backwards? What if the start is after the end?

std::vector<UINT32> backwardsClient(host.end(), host.begin());

// What happens?
like image 351
Lother Avatar asked Feb 14 '14 18:02

Lother


1 Answers

It will be undefined behavior.

Looking at the Standard:

N3690 23.3.7.2[vector.cons]

template <class InputIterator>
    vector(InputIterator first, InputIterator last,
    const Allocator& = Allocator());

9. Effects: Constructs a vector equal to the range [first,last), using the specified allocator.

It says that the range has to be [first, last), but the standard doesn't mention what happens if that isn't the case. It therefore is undefined behavior.

like image 98
AliciaBytes Avatar answered Sep 18 '22 02:09

AliciaBytes