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

How do I pass a list of values to a function expecting an array?

在我的程序中,我想将一些变量传递给一个函数,并让该函数 运行 有一个 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. You can upgrade to Visual 2013 (the Express Edition and 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;
}