c++ - 在不先构建数组的情况下将数字列表传递给 C++ 中的函数?

标签 c++ arrays function

我正在尝试构建一个以下列方式接受数组的函数:

int inCommon = findCommon({54,56,2,10}, 4);

int findCommon(int nums[], int len){
  for(int i=0; i<len; i++)  cout<<nums[i]<<endl;
  return 1;
} 

请注意,这实际上不是我的函数所做的,但我确实循环遍历了数组。我只是想确定是否可以传递像 {54,56,2,10} 这样的数组,而不必创建数组并传递它? (像这样:

int theArray[]= {54,56,2,10};
int inCommon = findCommon(theArray,4);

最佳答案

这在当时是不可能的。然而,在下一个 C++ 标准 C++0x 中,这将使用初始化列表来完成:

int findCommon(std::initializer_list<int> nums)
{
    std::initializer_list<int>::iterator it;
    for (it = nums.begin() ; it != nums.end() ; ++it)
    {
        std::cout << *it << std::endl;  
    }
    return 1;
}

参见 this presentation来自 Bjarne Stroustrup,和 this article来自维基百科

如果你想尝试 C++0x 的特性,你可以查看 last versions of gcc , 支持其中一些。

关于c++ - 在不先构建数组的情况下将数字列表传递给 C++ 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/643617/

相关文章:

c++ - 一种在再次打开文件之前知道文件当前是否打开的方法?

c++ - 在 Rcpp 中用(西类牙语)重音词对 map 进行排序

php - 将 php 数组数据插入 mysql 不起作用

javascript - 为什么 this.firstName 返回未定义?

c++ - 类函数的多定义错误

c++ - 如何使用模板方法避免循环依赖

C++ 元编程检测大小数组

php - 如何在 PHP 中对以逗号分隔的字符串进行排序?

python - Python中的函数和C++中的函数有什么区别?

function - AHK V2 如何在按钮的单击事件上调用函数