[英]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. 问题1>我找到了两种方法。 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? 问题2>我们无法从boost :: scoped_array获取有效长度吗?
Thank you 谢谢
Question 1: both methods are ok. 问题1:两种方法都可以。 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. 问题2:这是正确的,因为您无法获得传递给函数的C样式数组的长度。
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. boost::scoped_array
作为简单数组工作,你现在无法获得数据大小。 To copy it to vector you have to know it size. 要将其复制到矢量,您必须知道它的大小。 Here is link about scoped_array iterators and size.
这是关于scoped_array迭代器和大小的链接。
I'd select method 2: 我选择方法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: 当然,方法1也适用,例如动态数组:
vec.assign(&a[0], &a[9]+1); // => method one
As you can see - the method 2 just looks simpler, thus better. 正如您所看到的 - 方法2看起来更简单,因此更好。
And, no, there is no size()
method in scoped array. 并且,不,在作用域数组中没有
size()
方法。
Question 1: Both methods are correct. 问题1:两种方法都是正确的。
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 []
. 问题2:正确,它只是一个类似于std :: scoped_ptr的容器,它确保传递的指针(使用
operator new[]
手动创建)将使用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. 这两种方法对我来说都是正确的,但第二种方法肯定更清晰,因为你没有将偏移分成
9
和1
组件。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.