将几个数字作为一个数组参数传递给函数

Passing few numbers as a one array argument to function

本文关键字:数组 一个 参数传递 函数 几个 数字      更新时间:2023-10-16

嗨,我想传递1到10个参数给一个函数,这些参数将被保存在数组中。

function( 4, 3, 5); //calling function and passing arguments to it.
void function(int array[10])
{
    cout<<array[0];  // = 4
    cout<<array[1];  // = 3
    cout<<array[2];  // = 5
    cout<<array[3];  // = NULL or 0 or sth else
}

基本上我希望有机会传递任意多的参数,不多也不少

不可能是这样的。

    function( 4, 3, 5); //calling function and passing arguments to it.
    void function(int x1=NULL , int x2=NULL , int x3=NULL ,int x4=NULL , int x5=NULL)
    {
    for (int i=0 ; i<10;i++)
    {
        array[i] = x1;    // x2 , x3 and so on ...
    }
    cout<<array[0];  // = 4
    cout<<array[1];  // = 3
    cout<<array[2];  // = 5
    cout<<array[3];  // = NULL or 0 or sth else
    }

这是一个比这个例子更复杂的程序,所以我需要它是数组

一种方法是声明一个在头文件cstdarg中定义的验证函数。

不能说我真的用过它们,但是一个基本的方法来完成你似乎想做的事情,看起来像这样:

#include "stdarg.h"
void myfunction(int argcnt, ...){
  va_list args;
  int myarray[argcnt];
  va_start(args, argcnt);
  for(int i=0;i<argcnt;i++){
    myarray[i] = va_arg(args,int);
  }
  va_end(ap);
  // At this point, myarray[] should hold all of the passed arguments
  // and be ready to do something useful with.
}

在本例中,要处理的附加参数的数量在第一个参数中传递。所以要求:

myfunction(5,1,2,3,4,5);

将生成一个相当于myarray[5]={1,2,3,4,5}的局部变量

对于这种方法,Wikipedia上关于stdarg.h的条目也是一个相当不错的资源。此外,这个StackExchange讨论有一些关于更复杂实现的非常好的信息。

为什么不能直接传递一个数组的值和数组的长度?这样就能满足你的要求了。例子:

int main{
  int myArray[3] = { 4, 3, 5 };
  function( myArray, 3 );
}
void function( int * argsArray, int argsArrayLength ){
  int i;
  for( i = 0; i < argsArrayLength; i++ )
    cout << argsArray[i] << endl;
}

如果你使用的参数是常量表达式,你可以这样做:

template <int... Entries>
void function() {
    int array[sizeof...(Entries)] = {Entries...};
    for (int number : array) {
      std::cout << number << ' ';
    }
}

你可以这样使用它:

function<4,3,6>(); // prints "4 3 6"
相关文章: