How to copy data from `boost :: scoped_array` to` std :: vector`

vector<int> vec; boost::scoped_array<int> scpaInts; scpaInts.reset(new int[10]); for (int i=0; i<10; i++) scpaInts[i] = i*2; vec.assign(&scpaInts[0], &scpaInts[9]+1); // => method one vec.assign(scpaInts.get(), scpaInts.get()+10); // => method two 

Question 1> I figured out two methods. But I'm not sure if they are correct or there is a better way to do this.

Question 2> Is it true that we cannot get a valid length from boost :: scoped_array?

thanks

+7
source share
5 answers

Question 1: both methods are ok. A pointer to an array element can act as a random access iterator. It's also good.

 vec.assign(&scpaInts[0], &scpaInts[10]); 

Question 2: This is true for the same reason that you cannot get the length of the C-style array passed to the function.

+3
source

Both are fine. But the second is more clear to me. boost::scoped_array works like simple arrays, and now you cannot determine the size of the data. To copy it to a vector, you must know its size. Here is a link to scoped_array iterators and size.

+1
source

I would choose method 2:

 vec.assign(scpaInts.get(), scpaInts.get()+10); // => method two 

As for a regular dynamic array:

 int * a = new int[10]; ... vec.assign(a, a+10); // => method two 

Of course, method 1 also works, for example, with a dynamic array:

 vec.assign(&a[0], &a[9]+1); // => method one 

As you can see, method 2 just looks simpler the better.


And no, there is no size() method in an array with scope.

+1
source

Question 1: Both methods are correct.

Question 2: That's right, its just a container, similar to std :: scoped_ptr, which guarantees that the passed pointer (which was manually created using operator new[] ) will be deleted using operator delete [] . It does not contain any information about the size of the array.

+1
source

Both methods seem true to me, but the second is definitely understandable, since you do not divide the offset into components 9 and 1 . There are two more options:

 vec.assign(&scpaInts[0], &scpaInts[0] + 10); 

Or do not create a vector before you need it (best options):

 vector<int> vec(scpaInts.get(), scpaInts.get() + 10); 
+1
source

All Articles