将内联双精度数组作为方法参数传递

发布于 2024-12-25 03:38:12 字数 286 浏览 2 评论 0原文

考虑

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

热风软妹 2025-01-01 03:38:12

您可以使用 std::initializer_list<> 来完成此操作

#include<vector>

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

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

,它可以在 g++ 下编译并在指定的 -std=c++0x 下工作。

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.

浅笑依然 2025-01-01 03:38:12

这适用于 c++0x

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

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

虽然你需要确保在 functionA() 中删除了 new 分配的内存,否则将会出现内存泄漏!

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!

天气好吗我好吗 2025-01-01 03:38:12

您可以在 C++11 中使用 std::initializer_list 来完成此操作。

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

你不能在 C++03 中做到这一点(或者它将涉及足够的样板,这是不可行的)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文