【问题标题】:convert from float* to vector<float >从 float* 转换为 vector<float >
【发布时间】:2014-07-23 18:57:12
【问题描述】:

我有一个函数 float * pointwise_search(vector&lt;float &gt; &amp;P,vector&lt;float &gt; &amp;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&lt;float &gt; &amp;P,vector&lt;float &gt; &amp;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&lt;float&gt; P{p, p + num_thres}; 更改为vector&lt;float&gt; P(p, p + num_thres);。 :)

【问题讨论】:

  • 使用向量的迭代器对构造函数和数据的开始和结束指针。

标签: c++ matlab mex


【解决方案1】:

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

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

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

【讨论】:

  • ,嗨。我改为 float * pointwise_search(float p,float *q,int num_thres, float n, int len ) { vector P{p, p + num_thres};向量 Q{q, q + num_thres}; int size_of_threshold = P.size();...} 但出现错误。
  • 你是否在 C++11 模式下编译,例如-std=c++11 用于 clang 和 gcc?要么这样做(你应该这样做),要么将{} 更改为()
【解决方案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};

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多