如何在 C(首选)/C++ 中按顺序将一组 1D 数组传递给函数

How to sequentially pass a set of 1D arrays to a function, in C(preferred)/C++

本文关键字:1D 一组 数组 函数 首选 C++ 顺序      更新时间:2023-10-16

我有一组不同大小的一维数组,例如:

P1 [] = {0,2,5,6,9,8,7,55,7,4,1} 
P2 [] = {11,22,55,5,8,7,4,65,87,7,88,9,8,77,4,5,6,33,2,1,44,5,8,55} 
P3 [] = {0} 
//...
//...
Pn [] = { "","","","",...."",""} 

我想按顺序将这些数组传递给一个函数,比如 -
函数(Pi),其中I从1n变化。
我该怎么做?
所有一维数组在运行时之前都是已知的。内存需要优化,因此使用 2D 数组效率较低。

将所有数组的第一个元素的地址(即指向数组的第一个元素的指针)存储在另一个数组中,定义一个"指针数组",称为 pv

void * pv[] =
{
  P1, P2, P3, ..., Pn, NULL
};

然后遍历此数组的元素。

size_t i = 0;
while (NULL != pv[i])
{
  function(pv[i]);
  ++i;
}

但是请注意,您将丢失传递给function的数组的大小。

以下方法将不起作用:

void function(void * p)
{
  size_t s = sizeof p;
  ...

s指针的大小,通常为 4 或 8,具体取决于您的平台。

尽管仅仅达到 C 的极限试图解决这个问题并或多或少地使用机器人代码,但以下内容是可能的:

enum Type
{
  TypeInt,
  TypeCharPtr,
  ...
};
struct Array_Descriptor
{
  size_t s;
  void * p;
  enum Type t;
};
int P1 [] = {0,2,5,6,9,8,7,55,7,4,1};
int P2 [] = {11,22,55,5,8,7,4,65,87,7,88,9,8,77,4,5,6,33,2,1,44,5,8,55};
int P3 [] = {0};
...
char * Pn [] = { "","","","",...."",""};
struct Array_Descriptor ads[] =
{
  {sizeof P1/sizeof *P1, P1, TypeInt},
  {sizeof P2/sizeof *P2, P2, TypeInt},
  {sizeof P3/sizeof *P3, P3, TypeInt},
  ...
  {sizeof Pn/sizeof *Pn, Pn, TypeCharPtr},
};
...
size_t s = sizeof ads/sizeof *ads;
for (size_t i = 0; ; i < s; ++i)
{
  function(ads + i);
}

function的定义将更改为:

void function(struct Array_Descriptor * pad);

数据、元素数量和类型可通过以下方式访问

void function(struct Array_Descriptor * pad)
{
  void * p = pad->p;
  size_t s = pad->s;
  enum Type = pad->t;

下面是将多个数组传递给函数的示例。还有比这更好的方法。但是,我认为提供方向就足够了。

struct Aggregate
{
    void* ptr_array;
    size_t size;
};
void fun(Aggregate *aggr, size_t size)
{
        double *ptr = static_cast<double*>(aggr[1].ptr_array);
        int length = aggr[1].size;
        for ( int i = 0; i < length; i++ )
            cout << *(ptr+i) << endl;
}
int main()
{
    int arr[] = {1,2,3,4};
    double arr1[] = {1.0, 2.0};
    Aggregate *aggr = new Aggregate[2];   <<< You could remove this new if you know how many
    aggr[0].ptr_array = arr;              <<< arrays you are going to pass to fun
    aggr[0].size = 4;
    aggr[1].ptr_array = arr1;
    aggr[1].size = 2;
    fun(aggr, 2);
    delete [] aggr;         
}
void *pp[] = { P1, P2, P3, ..., PN };
for (size_t i = 0; i < sizeof(pp)/sizeof(pp[0]); i++)
    function(pp[i]);

使用 C++11 和可变参数模板,您可以执行以下操作

template <typename T, std::size_t N>
void Function(const T (&a)[N])
{
    // Your implementation
}
template <typename T, typename... Ts>
void Function(const T& t, const Ts&... args)
{
    Function(t);
    Function(args...);
}

现场示例