5

How do you copy the contents of an array to a std::vector in C++ without looping? has a great example how to simply copy the contents of an array into a vector.

Can you use the same technique to copy part of a vector into another vector?

e.g.

vector<int> v;

// ...v has some number of elements and we're interested in an 
// arbitrary number (y) from an arbitrary start point (x)...

vector<int> v2(&v[x], &v[x + y]);
Community
  • 1
  • 1
dlanod
  • 8,664
  • 8
  • 54
  • 96
  • 2
    If you are sure that `v` has at least `x+y` elements, you can use that exact notation. However, consider the answer by chris wich is more generic – Arne Mertz Jul 04 '13 at 07:35

2 Answers2

13

Yes, use iterators:

vector<int> v2(v.begin() + x, v.begin() + x + y);

You can make it a bit more generic if you wish:

vector<int> v2(std::next(std::begin(v), x), std::next(std::begin(v), x + y));

The reason the pointer version (which the array decays into for both arguments) works in the first place is that pointers can be treated as random-access iterators.

chris
  • 60,560
  • 13
  • 143
  • 205
  • 1
    I need to enable c++11 and `#include ` in latter case, am I right? – johnchen902 Jul 04 '13 at 07:35
  • Take advantage of ADL to save few keystrokes: `vector v2(std::next(begin(v), x), std::next(begin(v), x + y));` – Nawaz Jul 04 '13 at 07:56
  • I thought C++11 made `namespace std` an associated namespace of `std::vector::iterator`? Then the lookup of unqualified `next` should find `std::next`, right? (Save a few extra chars) – MSalters Jul 04 '13 at 08:38
  • @Nawaz, MSalters, Well, it would still become a bit less generic. You could use the same for an array, but the array would definitely not work with ADL. I'm a bit uncertain whether I like using ADL besides operators because the necessity of the qualification is usually prone to change depending on what you give it and it can confuse others (if they are unfamiliar with ADL) to see you need the qualification and then later see it work without the qualification, and have that fail later when they try it with something else. – chris Jul 04 '13 at 11:42
2

I believe this should work:

vector<int> v2( v.begin() + x, v.begin() + x + y );

There is more information in this other, previous answer: Best way to extract a subvector from a vector?

Community
  • 1
  • 1
Joe Z
  • 17,413
  • 3
  • 28
  • 39