代码之家  ›  专栏  ›  技术社区  ›  Perchik

在C++中,不先构建数组就将一系列数字传递给函数?

  •  4
  • Perchik  · 技术社区  · 17 年前

    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);
    
    5 回复  |  直到 17 年前
        1
  •  7
  •   Luc Touraille    17 年前

    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

        3
  •  2
  •   nan    17 年前

    不,我认为{}只能用于初始化数组。

        4
  •  2
  •   EvilTeach    17 年前
        5
  •  1
  •   bayda    17 年前

    不,这是不可能的。 但是你可以创建类似于模板T*arrayCreator(…)函数的东西,它将创建你的数组,
    或者具有未指定参数的构造函数的数组包装器计数。

    或者等待C++0x实现。