如何使用不同的参数多次调用函数

How do I call a function multiple times with different parameters?

本文关键字:调用 函数 参数 何使用      更新时间:2023-10-16

>在这里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 ,而不是以 null 结尾的字符串。

编辑后,看起来参数实际上应该是字符串,而不仅仅是字符,因此您需要一个字符串数组而不是字符数组。 所以你可以做一些类似的事情

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