“任意数量的参数”的问题是你怎么知道有多少。
std::min 和 std::min_element 通过在容器上工作来解决这个问题 - 换句话说,我们知道有多少,这要归功于容器对象本身知道有多少。
在纯 C 语言中,你不能真正做到这一点。所以需要有其他的方法。
一种方法是使用<cstdarg>,并用特殊值标记结尾:
#include <iostream>
#include <cstdarg>
using namespace std;
int countargs(int arg, ...)
{
if (arg == -1)
return 0;
int count = 1; // arg is not -1, so we have at least one arg.
va_list vl;
int cur;
va_start(vl, arg);
for(;;)
{
cur = va_arg(vl, int);
if(cur == -1)
break;
count++;
}
va_end(vl);
return count;
}
int main()
{
cout << "Should give 0: " << countargs(-1) << endl;
cout << "Should give 1: " << countargs(1, -1) << endl;
cout << "Should give 3: " << countargs(1, 2, 3, -1) << endl;
cout << "Should give 6: " << countargs(1, 2, 3, 1, 2, 3, -1) << endl;
cout << "Should give 12: " << countargs(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, -1) << endl;
return 0;
}
上面没有显示如何获得min 值,但应该不难弄清楚。它也是 C++,但不依赖于任何特殊的 C++ 功能。
“标记结束”的替代方法是将元素的数量传递给函数本身。
当然,如果参数在数组中,真正的解决方案是遍历它们。如果没有那么多,你当然可以使用:
v = min(a, min(b, min(c, d)));;