0

嗨,我想将十个参数传递给一个将保存在数组中的函数。

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
    }

它比这个例子更复杂,所以我需要它是数组。

4

3 回答 3

0

一种方法是声明头文件 cstdarg 中定义的 veridac函数

不能说我实际上已经将它们用于任何事情,但是完成您似乎想要做的事情的基本方法看起来像:

#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} 的局部变量

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

于 2013-05-30T20:35:16.800 回答
0

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

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"
于 2013-05-30T19:30:25.043 回答
0

为什么不能只传入一个值数组和数组的长度?看起来这几乎可以满足您的要求。例子:

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;
}
于 2013-05-30T19:23:23.887 回答