从float *转换为vector <float> </float>

时间:2014-07-23 18:57:13

标签: c++ matlab mex

我有一个功能 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]);错了。

所以我必须将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};更改为vector<float> P(p, p + num_thres);。 :)

2 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:2)

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

例如:

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

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