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

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

问题描述

我希望能够在 std::vector 与其底层 C 数组 int* 之间进行转换,而无需显式复制数据.

I would like to be able to convert between std::vector and its underlying C array int* without explicitly copying the data.

std::vector 是否提供对底层 C 数组的访问?我正在寻找这样的东西

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

另外,是否可以反过来,即如何在不复制的情况下从 C 数组初始化 std::vector?

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

这个指针只有在向量没有被重新分配时才有效.如果插入的元素多于向量剩余容量的容量(即,如果 v.size() + NumberOfNewElements > v.capacity(),则重新分配会自动发生.您可以使用 v.reserve(NewCapacity) 以确保向量至少具有 NewCapacity 的容量.

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::vector 和 C 数组之间转换而不复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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