简体   繁体   中英

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 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM