如何使用不同的参数多次调用函数
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
,而不是以 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
。
相关文章:
- 如何用参数值调用函数(仅在运行时已知)
- 从python中调用C++函数并获取返回值
- 当使用通配符和null指针调用函数时,对输出的说明
- 从R调用C++函数并对其进行集成时出错
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 如何在qt中从另一个类调用函数
- 在 COUT 语句中使用 COUT 调用函数
- 如何从线程中的不同模块调用函数?
- C++从函数指针数组调用函数
- 当 A 在 for 循环中调用函数 B 时,如何计算函数 A 的空间复杂度?
- 如何在 C/C++ 中从外部库调用函数
- 如何使用运算符在同一行中多次调用函数
- 是否可以创建一个从不同类调用函数的线程?
- 无法为类成员调用函数
- 如何从另一个标头 c++ 调用函数
- C++有什么方法可以在既不调用函数模板也不提供其模板参数的情况下引用函数模板?
- 如何只允许在调用函数 B 后调用函数 A?
- 我可以这样调用函数吗?
- 如何在 c++ 的类中递归调用函数方法?
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?