C ++ 11 Segmentation fault trying to copy an array (<algorithm>) to a vector dynamically

When I try to copy a fixed size array into a default constructed vector, I get a segfault. I am confused because I always thought vectors were flex containers that resize themselves to the dynamic data they consume. If I allocate space for a vector at compile time, but how can I copy that array to a vector without allocating the 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)

      

+3


source to share


1 answer


The target array must have a sufficient number of elements as a source. So use below to add new items as needed.

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

      



`

+3


source







All Articles