void printAllPermutations(string s)
{
// Sorting String
string temp(s);
sort(temp.begin(), temp.end());
// Print first permutation
cout << temp << endl;
// Finding the total permutations
int total = calculateTotal(temp, temp.length());
for (int i = 1; i < total; i++)
{
nextPermutation(temp);
}
}
int main()
{
string s = "AAB";
printAllPermutations(s);
} 字符串“%s”是函数printAllPermutations()的形参。我的疑问是:当's‘也是一个字符串,而'temp’是需要创建的新字符串时,"string temp(s);“是怎么写的?
发布于 2020-04-29 08:53:37
这句话
string temp(s);是temp的direct initialization。编译器将找到最匹配的构造函数重载,它将是string的复制构造函数。这意味着您实际上是从s复制构造temp,它等同于
string temp = s;这意味着temp将成为s的副本。
考虑到printAllPermutations函数通过值接受参数s,您实际上并不需要temp变量,您可以直接使用s,因为它将是您在调用printAllPermutations时使用的字符串的副本。
通过使用temp,您最初拥有字符串的三个副本:用于printAllPermutations调用的main函数中的原始字符串;s中的副本;以及temp中的副本。
实际上,您也不需要在main函数中使用s对象,您可以在函数调用中直接传递文字字符串"AAB":
printAllPermutations("AAB");https://stackoverflow.com/questions/61492387
复制相似问题