Why can we push_back a subvector defined only with range?

314 Views Asked by At

Say I have a vector<int> a = {1,2,3,4,5,6} and vector<vector<int>>b . Why can we write

b.push_back({a.begin() + 1, a.begin() + 4});

and end up with b = {{2345}}? I simplified this from a portion of code, so if this specific bunch of code doesn't work I will paste the actual code. I thought simplifying would help to understand the idea behind it.

1

There are 1 best solutions below

2
On
b.push_back({a.begin() + 1, a.begin() + 4});

is equivalent to:

std::vector<int> c{a.begin() + 1, a.begin() + 4};
b.push_back(c);

This is simply calling the std::vector constructor which accepts a pair of iterators and copies the values between those iterators into the new vector.