3

When I try to copy a fixed size array to a default constructed vector, I get a segfault. I'm confused because I always thought vectors are flexible containers which adjust their size to dynamic data they absorb. If I allocate space for the vector in compile time copying works but how can I copy this array into a vector without allocating a size at compile time?

int numbersArr[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
vector<int> NumbersVec; //Default constructor
// vector<int> NumbersVec(10); If I allocate the memory in compile time it works

copy(numbersArr, numbersArr + 10, NumbersVec.begin()); //Segmentation fault (core dumped)
moonwalker
  • 1,157
  • 1
  • 18
  • 34

1 Answers1

3

The destination array needs to have sufficient number of elements as the source. Therefore use below to add new elements as necessary.

#include <iterator>
copy(numbersArr, numbersArr + 10, back_inserter(NumbersVec));

`

911
  • 908
  • 8
  • 16
  • Thanks this works, but I'm still confused why so I looked up `back_inserter`: "A back-insert iterator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at the end of the container." So is this a problem with how `copy()` tries to overwrite existing elements and segfaults because it finds none? – moonwalker May 17 '15 at 14:05
  • 1
    what it says is copy overwrites elements if they exists. what you said in your question is right. vector is a dynamic container. However, to achieve that you have to use the methods like insert(), push_back(). back_inserter() returns a back_insert_iterator which handles insertion. – 911 May 17 '15 at 14:08