繁体   English   中英

从float *转换为vector <float >

[英]convert from float* to vector<float >

我有一个函数float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len )

我想matlab调用它所以我需要编写一个mexFunction。

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{ 
    if (nrhs != 4)
    {
        mexErrMsgTxt("Input is wrong!");
    }

    float *n = (float*) mxGetData(prhs[2]);
    int len = (int) mxGetScalar(prhs[3]);
    vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]);
    vector<float > Q= (vector<float >)mxGetPr(prhs[1]);

    plhs[1] = pointwise_search(Numbers,Q,n,len );

  }

但我发现vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]); vector<float > Q= (vector<float >)mxGetPr(prhs[1]); vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]); vector<float > Q= (vector<float >)mxGetPr(prhs[1]); 错了。

所以我必须将float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len )更改为float * pointwise_search(float *P,float *Q,float* n, int len )

根据答案,我改写如下

 float * pointwise_search(float p,float *q,int num_thres, float n, int len ) 
{    vector<float> P{p, p + num_thres}; 
     vector<float> Q{q, q + num_thres}; 
     int size_of_threshold = P.size();
...
} 

但是会出现错误。

pointwise_search.cpp(12) : error C2601: 'P' : local function definitions are illegal pointwise_search.cpp(11): this line contains a '{' which has not yet been matched

作为评论,我应该改变vector<float> P{p, p + num_thres}; to vector<float> P(p, p + num_thres); :)

当然你通常不能将指针转换为vector ,它们是不同的东西。 但是,如果指针保存已知长度的C样式数组的第一个元素的地址,则可以创建一个与数组具有相同内容的vector ,如:

std::vector<float> my_vector {arr, arr + arr_length};

其中arr表示指针, arr_length是数组的长度。 然后,您可以将vector传递给期望std::vector<float>&的函数。

如果你看一下这个std::vector构造函数引用 ,你会看到一个带有两个迭代器的构造函数(链接引用中的替代4)。 此构造函数可用于从另一个容器构造向量,包括数组。

例如:

float* pf = new float[SOME_SIZE];
// Initialize the newly allocated memory

std::vector<float> vf{pf, pf + SOME_SIZE};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM