Paradox
Paradox

Reputation: 2035

C++ Can't insert into empty vector

When I try to insert a vector into an empty vector I get a length error:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
  vector<int> v1;
  vector<int> v2 = {1};
  v1.insert(v2.begin(), v2.end(), v1.end());

}

and

terminate called after throwing an instance of 'std::length_error'
  what():  vector::_M_range_insert

Is this expected behavior? I thought insert would automatically increase the size of the vector if necessary. And it should insert right behind v1.end(), filling up the vector even if it is empty.

Upvotes: 0

Views: 780

Answers (1)

Charlie
Charlie

Reputation: 753

the correct syntax is:

v1.insert(v1.begin(), v2.begin(), v2.end());

or:

v1.insert(v1.end(), v2.begin(), v2.end());

Upvotes: 1

Related Questions