gpt4 book ai didi

c++ - 如何将值列表传递给需要数组的函数?

转载 作者:行者123 更新时间:2023-11-30 02:41:07 25 4
gpt4 key购买 nike

在我的程序中,我想将一些变量传递给一个函数,并让该函数运行一个 for 循环以将数据写入控制台。

这是我的代码:

void WriteValue(int[] arr)
{
for(auto c : arr)
std::cout<<arr<<std::endl;
}

int main()
{
int a = 0;
int b = 1;
int c = 3;

WriteValue(a,b,c);

return 0;
}

我知道这可以在 C# 中使用参数,但我没有那个选项。我如何让它在 C++ 中运行?

最佳答案

这里有一个非常简单灵活的方法:

#include <iostream>

template<typename T>
void WriteValue(const T& arr)
{
for(auto c : arr)
std::cout << c << std::endl;
}

int main()
{
int a = 0;
int b = 1;
int c = 3;

WriteValue(std::array<int, 3>{a,b,c});
// nicer C99 way: WriteValue((int[]){a,b,c});

return 0;
}

如果您只想传递一个整数列表(并且它必须是用大括号分隔的列表,而不是现有数组),您可以改为这样做

#include <iostream>
#include <initializer_list>

void WriteValue(const std::initializer_list<int>& arr)
{
for(auto c : arr)
std::cout << c << std::endl;
}

int main()
{
int a = 0;
int b = 1;
int c = 3;

WriteValue({a,b,c});

return 0;
}

不幸的是,VS2012 doesn't support this.您可以升级到 Visual 2013(速成版和 Community Edition 都是免费的),或者您可以使用辅助变量:

#include <iostream>

template<typename T>
void WriteValue(const T& arr)
{
for(auto c : arr)
std::cout << c << std::endl;
}

int main()
{
int a = 0;
int b = 1;
int c = 3;

int args[] = { a, b, c };
WriteValue(args);

return 0;
}

关于c++ - 如何将值列表传递给需要数组的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28445350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com