C ++ - 指针数组向量? [英] C++ - pointer array to Vector?

查看:165
本文介绍了C ++ - 指针数组向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double * values; // instead of this,
std::vector<double> values; // I want this.

我使用的API提供的结果为 double * 指针。我想用 std :: vector< double> 类型来包装。

An API I'm using provides a result as double* pointer. I want to wrap this with the std::vector<double> type.

推荐答案

您不能将数组包含在向量中 ,并期望向量对该数组进行操作。你可以做的最好的办法是给向量 double * 和值的数量,这将使向量复制每个元素并将其放在自身: p>

You can't wrap an array in a vector in place and expect the vector to operate on that array. The best you can do is give the vector the double* and the number of values, which will have the vector make a copy of every element and put it in itself:

int arrlen = 0;

// pretending my_api takes arrlen by reference and sets it to the length of the array
double* dbl_ptr = my_api(arrlen); 

vector<double> values(dbl_ptr, dbl_ptr + arrlen);

// note that values is *not* using the same memory as dbl_ptr
// so although values[0] == dbl_ptr[0], &values[0] != &dbl_ptr[0]

而且,如Praetorian所说,如果你使用的API期望你在使用后释放内存,你可能会对智能指针感兴趣。请参见 Praetorian的回答

And also, like Praetorian said, if the API you are using expects you to free the memory after using it, you might be interested in smart pointers. See Praetorian's answer.

这篇关于C ++ - 指针数组向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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