How to efficiently prepend a vector to a vector

Viewed 300

I have 2 vectors like so:

std::vector<unsigned char> v1;
std::vector<unsigned char> v2;

Each of them has some data of course.

I know that following is the way if I want to append v2 to v1. v1.insert(v1.end(), v2.begin(), v2.end());

Question:
How can I prepend v1 to v2 instead?
v2.insert(v2.begin(), v1.begin(), v1.end()) doesn't seem to work here?

I know that I might get suggestions of using std::deque instead but the problem is that v2 is coming as a std::vector out of a function in a legacy piece of code which I cannot change. And it contains a huge amount of data which I do not want copy over to v2 by appending. So, I simply want to prepend v1 to v2 because v1 is extremely small compared to v2

1 Answers

This does work very well:

std::vector<int> a{ 1,2,3,4 };
std::vector<int> b{ 5, 6, 7 };
a.insert(a.begin(), b.begin(), b.end());
// a is  {5, 6, 7, 1, 2, 3, 4}

What problem did you face?

Related