将内联双精度数组作为方法参数传递
考虑
functionA (double[] arg)
我想要内联传递一个双数组的方法,就像
functionA({1.9,2.8})
而不是先创建一个数组然后传递它,就像
double var[] = {1.0,2.0};
functionA(var);
这在 C++ 中可能吗?听起来很简单,但无论如何我都找不到关于我的问题的提示,这让我很怀疑:)。
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 :).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
std::initializer_list<>
来完成此操作,它可以在 g++ 下编译并在指定的
-std=c++0x
下工作。You can do this with
std::initializer_list<>
Which compiles and works for me under g++ with
-std=c++0x
specified.这适用于 c++0x
虽然你需要确保在 functionA() 中删除了 new 分配的内存,否则将会出现内存泄漏!
This works with c++0x
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!
您可以在 C++11 中使用
std::initializer_list
来完成此操作。你不能在 C++03 中做到这一点(或者它将涉及足够的样板,这是不可行的)。
You can do it in C++11 using
std::initializer_list
.You can't do it in C++03 (or it will involve enough boilerplate it won't be feasible).