0

Which is the best way to extract part of a vector? If I have

std::vector<int> v1(9);

for(int i = 0; i < 9; i++)
    v1[i] = i + 1;

I need a code that put in

std::vector<int> v2(2);

the second and third element of v1. I have to do a cycle or there is a smartest way?

Wellen
  • 51
  • 7

2 Answers2

5

Try this using the iterator form of vector constructor

 std::vector<int> v2(v1.begin() + 1,v1.begin() + 3);

If v2 already exists use assign

v2.assign(v1.begin() + 1,v1.begin() + 3);
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
2

You can use std::copy(), Suppose if you want to insert 1st and 2nd element from v1 to the beginning of v2 then you can use following.

std::copy ( v1.begin()+1, ,v1.begin() + 3, v2.begin() );
Shrikant
  • 744
  • 8
  • 18