我正在尝试构建一个以下列方式接受数组的函数:
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/