I'm trying to understand the behavior of creating a subvector of another vector.
For example, this code: https://godbolt.org/z/PYG34vnTr has a 2-element vector vec1. I want to create a vector of the first element. To get it to work, I had to use:
std::vector<int> vec2 = {vec1.begin(), vec1.begin() + 1};
I'm trying to understand why this is needed. Reason being, I'm doing a recursive loop that halves a vector in each iteration. And the formula:
std::vector<int> vec2 = {vec1.begin(), vec1.begin() + (vec1.size()-1)/2};
Works for all iterations except the one where vec1 is a 2-element vector.
What alternative code should I use?
The end iterator needs to be 1 element beyond the last element you want, which means that the
-1must be removed.Illustration:
Output:
Demo
A non-copying version, working solely with iterators could look like this and gives the same result:
Demo