I have a function
float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len )
.
I want matlab call it so I need to write a 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 );
}
But I found that vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]);
vector<float > Q= (vector<float >)mxGetPr(prhs[1]);
are wrong.
So I have to change float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len )
to float * pointwise_search(float *P,float *Q,float* n, int len )
.
According to the answers, I rewrite as the following
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();
...
}
But there occur errors.
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
As the comment,I should change vector<float> P{p, p + num_thres};
to vector<float> P(p, p + num_thres);
. :)
Of course you can not generally convert a pointer to a vector
, they are different things. If however the pointer holds the address of the first element of a C-style array of known length, you can create a vector
with the same contents as the array like:
std::vector<float> my_vector {arr, arr + arr_length};
where arr
is said pointer and arr_length
is the length of the array. You can then pass the vector
to the function expecting std::vector<float>&
.
If you look at e.g. this std::vector
constructor reference, you will see a constructor which takes two iterators (alternative 4 in the linked reference). This constructor can be used to construct a vector from another container, including arrays.
For example:
float* pf = new float[SOME_SIZE];
// Initialize the newly allocated memory
std::vector<float> vf{pf, pf + SOME_SIZE};
来源:https://stackoverflow.com/questions/24918686/convert-from-float-to-vectorfloat