有什么方法可以编写一个采用数组类型的可变参数函数?
void compare(int count ...) {
double[2] condition;
va_list vl;
va_start(vl, count);
for (int i = 0; i < count; i++){
condition = va_arg(vl, double[2]);
// do something with condition
}
va_end(vl);
}
我尝试用C ++进行操作,但是我的程序说double[2]
类型是不可分配的。
有什么解决办法吗?
答案 0 :(得分:3)
固定数组衰减为指向第一个元素的指针。
数组总是通过指针传递给C风格可变参数,例如:
void compare(int count, ...)
{
double *condition;
va_list vl;
va_start(vl, count);
for (int i = 0; i < count; ++i)
{
condition = va_arg(vl, double*);
// do something with condition up to 2 elements
}
va_end(vl);
}
int main()
{
double arr1[2] = {1, 2};
double arr2[2] = {3, 4};
double arr3[2] = {5, 6};
compare(3, arr1, arr2, arr3);
return 0;
}
如果您需要知道每个传递数组的长度,则必须使用其他可变参数传递该信息,例如:
void compare(int count, ...)
{
double *condition;
int len;
va_list vl;
va_start(vl, count);
for (int i = 0; i < count; ++i)
{
len = va_arg(vl, int);
condition = va_arg(vl, double*);
// do something with condition, up to len elements
}
va_end(vl);
}
int main()
{
double arr1[1] = {1};
double arr2[5] = {2, 3, 4, 5, 6};
double arr3[2] = {7, 8};
compare(3, 1, arr1, 5, arr2, 2, arr3);
return 0;
}
如果您使用的是C ++ 11或更高版本,则应使用C ++样式variadic templates而不是C样式可变参数,例如:
template <size_t N>
void doSomething(double (&condition)[N])
{
// do something with condition, up to N elements
}
template <size_t N>
void compare(double (&arr)[N])
{
doSomething(arr);
}
template <size_t N, typename... Args>
void compare(double (&arr)[N], Args&... args)
{
doSomething(arr);
compare(args...);
}
int main()
{
double arr1[1] = {1};
double arr2[5] = {2, 3, 4, 5, 6};
double arr3[2] = {7, 8};
compare(arr1, arr2, arr3);
return 0;
}