Passing inline double array as method argument

我怕爱的太早我们不能终老 提交于 2019-12-10 12:38:06

问题


Consider method

functionA (double[] arg)

I want to pass a double array inline, like

functionA({1.9,2.8})

and not create an array first and then pass it, like

double var[] = {1.0,2.0};
functionA(var);

Is this possible with C++? Sounds simple, but I could not find a hint anyway concerning my question which made me suspicious :).


回答1:


You can do this with std::initializer_list<>

#include<vector>

void foo(const std::initializer_list<double>& d)
{ }

int main()
{
    foo({1.0, 2.0});
    return 0;
}

Which compiles and works for me under g++ with -std=c++0x specified.




回答2:


This works with c++0x

void functionA(double* arg){
   //functionA
}

int main(){
    functionA(new double[2]{1.0, 2.0});
    //other code
    return 0;
}

Although you need to make sure that the memory allocated by new is deleted in the functionA(), failing which you there will be a memory leak!




回答3:


You can do it in C++11 using std::initializer_list.

void fun(std::initializer_list<double>);
// ...
fun({ 1., 2. });

You can't do it in C++03 (or it will involve enough boilerplate it won't be feasible).



来源:https://stackoverflow.com/questions/8739358/passing-inline-double-array-as-method-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!