如何在 C(首选)/C++ 中按顺序将一组 1D 数组传递给函数
How to sequentially pass a set of 1D arrays to a function, in C(preferred)/C++
我有一组不同大小的一维数组,例如:
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从1
到n
变化。
我该怎么做?
所有一维数组在运行时之前都是已知的。内存需要优化,因此使用 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...);
}
现场示例
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 一组值的零开销下标运算符
- 使用一组结构,避免在一组结构中出现重复的结构
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 如何从一组变量中查找最低值
- 如何使用指针C++将元素从2D数组复制到1D数组
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何通过查找迭代器结果分配给一组对的元素
- 读取一组用户输入,按升序排序,然后打印结果
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 在 c++ 中定义一组 set 的迭代器
- 使用 C++20 概念强制类实现一组方法
- 如何在 C(首选)/C++ 中按顺序将一组 1D 数组传递给函数