【发布时间】:2021-10-09 04:21:51
【问题描述】:
在Java 我们有variable arguments 这个语法告诉编译器fun() 可以用零个或多个参数调用。因此,这里的 a 被隐式声明为 int[] 类型的数组。
class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);
// using for each loop to display contents of a
for (int i: a)
System.out.print(i + " ");
System.out.println();
}
// Driver code
public static void main(String args[])
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}
我希望在C++ 中实现相同的功能,但我找不到任何有用的东西。有人有什么想法吗?
【问题讨论】:
-
C++ 中只有可变参数,但它是无类型的
-
@xskxzr 似乎很相关,但我不太了解。
-
@phuclv 这个问题是关于 Python,而不是 C++。
-
@chrylis-cautiouslyoptimistic- 是的,我没有仔细阅读。真实重复:C++11 variable number of arguments, same specific type、Variable number of parameters in function in C++、Variable number of arguments in C++?
-
如果参数在编译时已知,您可能需要parameter pack。如果您直到运行时才知道,请将参数推送到
std::vector,然后传入vector。在 C++ 中为您完成所有解决方案并不容易,主要是因为它几乎是隐藏在 syntactic sugar 层后面的vector选项,而 C++ 不赞成隐藏可能会产生大量开销的东西。
标签: java c++ algorithm data-structures