![](/img/trans.png)
[英]How do I use a “wrapper function” to call a recursive function without parameters n amount of times?
[英]How do I call a function multiple times with different parameters?
这里对 C++ 相当陌生。 我想知道是否可以通过不多次调用同一个函数来优化我的代码。 例如见下: funcCall 是一个独立的函数,所以它不能被删除,它需要知道的只是这三个参数..
const char *a = "H";
const char *b = "e";
const char *c = "l";
const char *d = "l";
const char *e = "o";
const char *f = "Hi";
funcCall(f,a,b);
funcCall(f,c,d);
funcCall(f,d,e);
void funcCall(const char *one, const char *two, const char *three)
{
//Kindly ignore the syntax
//open the file and write the first two parameters to it
fopen(three.txt);
fwrite(one,two,three.txt); //ignore syntax
fclose(three.txt);
}
您可以创建一个字符数组,并一次循环两个,如下所示:
char abcdef[] = "Helllo";
const char* hi = "Hi";
for (char* p = abcdef; p < abcdef + 6; p += 2) {
funcCall(hi, p[0], p[1]);
}
这与您的示例的不同之处在于它将字符作为第二个和第三个参数传递给funcCall
,而不是以空字符结尾的字符串。
编辑后,看起来参数实际上应该是字符串,而不仅仅是字符,因此您需要一个字符串数组而不是字符数组。 所以你可以做类似的事情
std::vector<const char*> args = {"One", "Two", "Three"};
std::vector<const char*> files = {"A.txt", "B.txt", "C.dat"};
const char* hi = "Hi";
for (int i = 0; i < std::min(args.size(), files.size()); ++i) {
funcCall(hi, args[i], files[i]);
}
其中funcCall
采用const char*
参数,如您的示例所示。 (最好使用std::string
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.