[英]Repeated Function call in the following program in C++
I have to write a programs that takes an input of string which has some '$' and digits.我必须编写一个程序,该程序需要输入包含一些“$”和数字的字符串。 The output of the program is set of all possible strings where the '$ in the string is replaced by all the other digits.
程序的 output 设置了所有可能的字符串,其中字符串中的 '$ 被所有其他数字替换。 I have written the following code for it.
我为此编写了以下代码。
#include<bits/stdc++.h>
using namespace std;
int numberOf(string in)
{
int count = 0;
for(int i = 0; i <= in.size()-1; i++)
if(in[i] == '$')
count++;
return count;
}
void solve(string in, string in1, vector <string> &s,
int index)
{
if(numberOf(in) == 0)
{
s.push_back(in);
return;
}
if(index == in.size())
{
return;
}
if(in1.empty())
{
return;
}
else
{
if(in[index] == '$')
{
string in2 = in;
in2[index] = in1[0];
string in3 = in1;
in3.erase(in3.begin());
solve(in2, in1, s, index+1);
solve(in, in3, s, index);
return;
}
else
{
solve(in, in1, s, index+1);
return;
}
}
}
void replaceDollar(string in)
{
string in1 = in;
int count = 0;
for(int i = 0; i <= in.size()- 1; i++)
{
if(in[i] != '$')
{
in1.push_back(in[i]);
count++;
}
}
count = in.size() - count;
cout << "Number is " << count << "\n";
vector <string> s;
solve(in, in1, s, 0);
for(auto i = s.begin(); i != s.end(); i++)
cout << *i << " ";
cout << "\n";
}
int main()
{
int t;
cin >> t;
while(t--)
{
string in;
cin >> in;
replaceDollar(in);
}
return 0;
}
For following input对于以下输入
1
$45
The expected output should be预期的 output 应该是
445 545
But it returns但它返回
445 545 445 545
Can anyone please explain why is it outputting repeated strings?谁能解释为什么它输出重复的字符串? Also can anyone suggest a better approach to this question?
也有人可以提出更好的方法来解决这个问题吗? Thanks in advance!
提前致谢!
Assuming that this is homework:假设这是家庭作业:
char
char
类型std::string::replace()
to replace each instance of $
with each digit.std::string::replace()
用每个数字替换$
的每个实例。std
libraries, then add another loop and compare yourself. std
库,那么添加另一个循环并自己比较。$
with $
$
替换$
stdout
as you create them.stdout
。 See this post:看到这个帖子:
How to replace all occurrences of a character in string? 如何替换字符串中所有出现的字符?
ps Pro tip: don't use using namespace
. ps 专业提示:不要使用
using namespace
。 Use the full namespace in your calls;在你的调用中使用完整的命名空间; eg:
例如:
Bad坏的
using namespace std;
string = "hello world";
Good好的
std::string = "hello world";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.