2

Is there a method to add a vector at the end of another vector? For example if my vectors are

std::vector<int> v1(3);
std::vector<int> v2(3);

/* ... initialize vectors ... */
/* ... for example, v1 is 1 2 3 and v2 is 4 5 6 ... */

which is the smartest way to add v2 at the end of v1 (i.e. to obtain v1 = 1 2 3 4 5 6) without using a cycle and a push_back?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Wellen
  • 51
  • 7

1 Answers1

10

You can use insert:

vec1.insert(vec1.end(), vec2.begin(), vec2.end());

This will add all the elements in the range [vec2.begin(), vec2.end()) (that is, all the elements in vec2) to vec1, starting at position vec1.end() (that is, right after all the elements of vec1).

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • I remember when I first learned about iterators... it was amazing. I'm still impressed by the flexibility of the system. – ApproachingDarknessFish Jan 30 '14 at 21:46
  • And if I want to add to v1 the second and third element of v1 what I have to do? (ie I want as result v1 = 1 2 3 2 3) – Wellen Jan 30 '14 at 22:12
  • @Wellen You'd have to manually insert the elements one at a time. You might want to look up a tutorial on containers, iterators, and algorithms for examples of how to do this. – templatetypedef Jan 30 '14 at 22:16
  • these are bad news... there isn't a method that return the iterator to the 'i' element? – Wellen Jan 30 '14 at 22:19