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(;"?
语句
string temp(s);
是CCD_ 1的直接初始化。编译器将找到最匹配的构造函数重载,它将是string
的复制构造函数。这意味着您真正从s
复制构造temp
,它相当于
string temp = s;
这意味着temp
将是s
的副本。
考虑到printAllPermutations
函数按值接受参数s
,您实际上并不需要temp
变量,您可以直接处理temp
0,因为它将是您在调用printAllPermutations
时使用的字符串的副本。
通过使用temp
,您最初有三个字符串副本:main
函数中用于printAllPermutations
调用的原始字符串;s
中的副本;以及temp
中的副本。
实际上,main
函数中也不需要对象s
,您可以在函数调用中直接传递文本字符串"AAB"
:
printAllPermutations("AAB");