C ++的std ::向量和C数组之间的转换,而不复制 [英] Converting between C++ std::vector and C array without copying

查看:222
本文介绍了C ++的std ::向量和C数组之间的转换,而不复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想是能够的std :: vector和其底层C数组为int *之间的转换没有明确复制数据。

有没有性病::矢量提供访问底层的C数组?我期待这样的事情

 矢量<&INT GT; V(4100)
为int * PV = v.c_array();

编辑:

此外,是有可能做相反的,即我将如何初始化一个的std ::矢量从C数组没有复制?

  INT PV [4] = {4,4,4,4};
矢量<诠释> V(PV);


解决方案

您可以得到一个指向第一个元素如下:

 为int * PV =&放大器; v [0];

此指针是唯一有效的,只要该载体不重新分配。如果插入比将适合的载体的剩余容量更多的元素(即,如果 v.size()+ NumberOfNewElements&GT再分配自动发生; v.capacity()你。可以使用 v.reserve(NewCapacity)来确保向量的容量至少 NewCapacity

还记得,当载体被破坏,底层数组被删除。

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

解决方案

You can get a pointer to the first element as follows:

int* pv = &v[0];

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 use v.reserve(NewCapacity) to ensure the vector has a capacity of at least NewCapacity.

Also remember that when the vector gets destroyed, the underlying array gets deleted as well.

这篇关于C ++的std ::向量和C数组之间的转换,而不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆