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 have figured out two methods. But I am not sure whether they are correct or there is a better way to do this.
Question 2> Is it true that we cannot get the valid length from boost::scoped_array?
Thank you
Question 1: both methods are ok. A pointer to an element of an array can play a role of a random-access iterator. This one is fine as well
vec.assign(&scpaInts[0], &scpaInts[10]);
Question 2: That is true for the same reason that you can't get the length of an C-style array passed to a function.
Both are ok. But the second one is more clear for me. boost::scoped_array
works as simple arrays and you cant now the size of data. To copy it to vector you have to know it size.
Here is link about scoped_array iterators and size.
I'd select method 2:
vec.assign(scpaInts.get(), scpaInts.get()+10); // => method two
Like for ordinary dynamic array:
int * a = new int[10];
...
vec.assign(a, a+10); // => method two
Of course method 1 works too, like for example with dynamic array:
vec.assign(&a[0], &a[9]+1); // => method one
As you can see - the method 2 just looks simpler, thus better.
And, no, there is no size()
method in scoped array.
Question 1: Both methods are correct.
Question 2: Correct, its just a container similar to std::scoped_ptr, which makes sure that the pointer passed (which was manually created using operator new[]
) will be deleted using operator delete []
. It doesn't hold any information about the size of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With