0

i'm trying to extract a subvector of int from another subvector of int using iterator with this code :

std::vector<int> Original; std::vector<int> NewVec;
NewVec(Original.begin(), Original.begin()+5);

and this doesn't work, only if i declare NewVec in the same line of extraction like that :

std::vector<int> NewVec(Original.begin(), Original.begin()+5);

So, is it possible to use NewVec such that its declaration is before its construction ? Thanks.

user3359851
  • 13
  • 1
  • 4

2 Answers2

6

If you want to assign a subrange to an existing std::vector you can use the assign() member:

NewVec.assign(Original.begin(), Original.begin() + 5);

Of course, this assumes that Original has at least 5 elements.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • for learners) `assign` resets the vector. i.e. the original elements of the `NewVec` in the above code are all removed. – starriet Jul 06 '23 at 10:43
2

You can use std::copy:

NewVec.reserve(5);
std::copy(std::begin(Original), std::begin(Original)+5,
          std::back_inserter(NewVec));

Or std::vector::assign:

NewVec.assign(std::begin(Original), std::begin(Original)+5);
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • what if you don't use `reserve` or `resize`? – Jepessen Dec 03 '15 at 09:32
  • @Jepessen `reserve` is just to avoid unnecessary allocations when inserting into the vector. In this case I doubt it'd make any difference as the vector is very small, but I tend to `reserve` whenever I `std::copy` so that I don't forget when it matters. – TartanLlama Dec 03 '15 at 09:33
  • @Jepessen: the `reserve()` is a potential optimization, avoiding relocation of the `std::vector`'s element. The `resize()` in the above use is unnecessary. – Dietmar Kühl Dec 03 '15 at 09:34
  • Ok got it. So it's a performance issue... thanks for explanation. – Jepessen Dec 03 '15 at 09:34