C++ 之间的转换std::vector 和 C 数组,无需复制
我希望能够在 std::vector 及其底层 C 数组 int* 之间进行转换,而无需显式复制数据。
std::vector 是否提供对底层 C 数组的访问?我正在寻找类似这样的东西
vector<int> v (4,100)
int* pv = v.c_array();
编辑:
另外,是否可以进行相反的操作,即如何从 C 数组初始化 std::vector
而不进行复制?
int pv[4] = { 4, 4, 4, 4};
vector<int> v (pv);
I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data.
Does std::vector provide access to the underlying C array? I am looking for something like this
vector<int> v (4,100)
int* pv = v.c_array();
EDIT:
Also, is it possible to do the converse, i.e. how would I initialize an std::vector
from a C array without copying?
int pv[4] = { 4, 4, 4, 4};
vector<int> v (pv);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以按如下方式获取指向第一个元素的指针:
该指针仅在向量未重新分配时才有效。如果您插入的元素多于向量的剩余容量(即,如果
v.size() + NumberOfNewElements > v.capacity()
),则会自动进行重新分配。您可以使用v .reserve(NewCapacity)
以确保向量的容量至少为NewCapacity
。还要记住,当向量被销毁时,底层数组也会被删除。
You can get a pointer to the first element as follows:
This pointer is only valid as long as the vector is not reallocated. Reallocation happens automatically if you insert more elements than will fit in the vector's remaining capacity (that is, if
v.size() + NumberOfNewElements > v.capacity()
. You can usev.reserve(NewCapacity)
to ensure the vector has a capacity of at leastNewCapacity
.Also remember that when the vector gets destroyed, the underlying array gets deleted as well.
在 C++11 中,您可以使用 vector::data()获取C数组指针。
In C++11, you can use vector::data() to get C array pointer.
请注意,这仅适用于
std::vector
,您不能对其他标准容器(std::string
除外)执行相同的操作。斯科特·迈耶斯在他的书中广泛讨论了这个主题。
Note that this is only the case for
std::vector<>
, you cannot do the same with other standard containers (except forstd::string
).Scott Meyers covers this topic extensively in his books.
如果您的条件非常受控,您可以这样做:
请注意,只有在向量不必增长的情况下,这才会起作用,并且向量仍将管理底层数组的生命周期(也就是说,不要不要删除 pv)。在调用底层 C API 时,这种情况并不罕见,但通常是使用未命名的临时变量来完成,而不是通过创建显式的 int* 变量来完成。
If you have very controlled conditions, you can just do:
Be warned that this will only work as long as the vector doesn't have to grow, and the vector will still manage the lifetime of the underlying array (that is to say, don't delete pv). This is not an uncommon thing to do when calling underlying C APIs, but it's usually done with an unnamed temporary rather than by creating an explicit int* variable.
保护自己免受大小变化影响的一种方法是保留所需的最大空间(或更大):
这将确保 push_backs 不会导致现有数据的重新分配。
One way of protecting yourself against size changes is to reserve the maximal space (or larger) that you will need:
This will ensure that push_backs won't cause reallocation of the existing data.