Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

std

stl

boost

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

like image 853
q0987 Avatar asked Oct 26 '12 14:10

q0987


4 Answers

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.

like image 52
Andrey Avatar answered Nov 13 '22 19:11

Andrey


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.

like image 39
Denis Ermolin Avatar answered Nov 13 '22 20:11

Denis Ermolin


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.

like image 35
PiotrNycz Avatar answered Nov 13 '22 18:11

PiotrNycz


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.

like image 40
Stacker Avatar answered Nov 13 '22 19:11

Stacker