Reputation: 35992
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
Upvotes: 7
Views: 5997
Reputation: 96301
Both methods seem correct to me, but the second is definitely clearer since you aren't splitting the offset into 9
and 1
components. There are also two other options:
vec.assign(&scpaInts[0], &scpaInts[0] + 10);
Or don't create the vector before you need it (best of all the options):
vector<int> vec(scpaInts.get(), scpaInts.get() + 10);
Upvotes: 1
Reputation: 1210
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.
Upvotes: 1
Reputation: 24430
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.
Upvotes: 1
Reputation: 8604
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.
Upvotes: 3
Reputation: 5556
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.
Upvotes: 1