Hi all, this is my first post here and it comes out of frustration more than anything. I've been searching high and low for any insight into my problem and still can't seem to get it right. In the interest of full disclosure, this is a part of a homework problem and I'm not asking for anyone to solve the problem, I just need some help with this part. We're playing around with STL containers and algorithms and I need to copy an array of random characters into a vector using the copy() algorithm. As I understand I'm going to need a pointer to the beginning of the array and a pointer to the end of the array. So I have my array called data that has 25 characters in it, then I would need to make a pointer to the beginning char* dataBegin = &data[0] and to the end char* dataEnd = &data[24]. Then I used those in the copy algorithm by typing - copy(dataBegin, dataEnd, charVector.begin()) - where charVector is the vector I'm trying to copy into. Everything I've read says thats the proper format the copy algorithm but when I compile and run, it seg faults every time. Does anything that I've put jump out as an error I've made? Thanks for the help.

>Does anything that I've put jump out as an error I've made?
Yes, I see one problem if the vector doesn't already have a size equal to or greater than the size of the array: copy doesn't call push_back, it performs a direct assignment. I'd do something more like this:

#include <algorithm>
#include <iterator>
#include <vector>

const int n = 25;

int a[n];
std::vector<int> v;

//...

std::copy ( a, a + n, std::back_inserter ( v ) );

Wow that worked perfectly, thank you so much. But if I might ask one more question - is there a way to accomplish this without using the iterator header file and the back_inserter? Thank you again.

If you want to use the copy template, really all you can do is make sure the vector is sized correctly:

v.resize ( n );
std::copy ( a, a + n, v.begin() );

Alternatively, you can do this straight from the constructor of the vector object and not have to worry about any of that stuff:

std::vector<int> v ( a, a + n );

Awesome, that way works too. Thanks so much for the help, I'm going to go ahead and mark my post solved. Thank you again.

This question has already been answered. Start a new discussion instead.