1

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Blue
  • 29
  • 2
  • 4
    Because the author of the STL has it designed in that way. What is the problem? The question? – Klaus Oct 24 '20 at 07:48
  • ... and how you want to describe a subvector without giving the range? – Klaus Oct 24 '20 at 07:57
  • Have you *tried* it? What happens when you do? – Some programmer dude Oct 24 '20 at 07:59
  • Why is this question closed? It is a very specific syntax with a very specific answer why it works (I mean, the given answer doesn't explain it well, but automatic casts could be explained here). – Frax Oct 25 '20 at 09:15
  • I mean, I'd like to see the language lawyer answer here, but the question is closed instead. – Frax Oct 25 '20 at 09:21

1 Answers1

1
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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • Naturally, `b.emplace_back(a.begin() + 1, a.begin() + 4);` is potentially more efficient. – Deduplicator Oct 24 '20 at 08:19
  • @Deduplicator shouldn't make much if any difference, the vector in the original code is a temporary so should be moved anyway so it's only one move constructor you'd avoid using `emplace_back` – Alan Birtles Oct 24 '20 at 08:51