[英]How can I write a recursion function with a vector parameter?
I have a function that takes a vector as a parameter, scan this vector and generates a random word.我有一个 function ,它以一个向量作为参数,扫描这个向量并生成一个随机词。 It's expected from me that the generated words' letters are different from each other.我期望生成的单词的字母彼此不同。 So, I want to check it with a simple if-else condition inside the same function.所以,我想在同一个 function 中用一个简单的 if-else 条件来检查它。 If all letters are different, function returns this word.如果所有字母都不同,则 function 返回此单词。 If not, I need to use the same function which I am already inside while using conditions.如果没有,我需要使用相同的 function 在使用条件时我已经在里面。 But first parameter that I used in the main function doesn't work when I attempt to use it for the second time.但是当我第二次尝试使用它时,我在主 function 中使用的第一个参数不起作用。 Here the generateaRandomWord(vector a) function:这里生成aRandomWord(vector a) function:
vector<string> currentVector;
string generateaRandomWord(vector<string> a) {
currentVector = a;
string randomWord;
int randomNumber = rand() % currentVector.size();
randomWord = currentVector.at(randomNumber);
if (hasUniqueChars(randomWord)) {
return randomWord;
}
else {
generateaRandomWord(currentVector);
}
}
I thought that it is a good idea to keep a vector (currentVector) outside of the function.我认为在 function 之外保留一个向量(currentVector)是个好主意。 So, for the first time I use the function this vector will be defined and I will be able to use it if using recursion is necessary.所以,我第一次使用 function 这个向量将被定义,如果需要使用递归,我将能够使用它。 But that didn't work either.但这也没有用。
The main problem you have is that your recursive case doesn't return anything -- it throws away the returned value from the recursive call, then falls off the end of the function (returning garbage -- undefined behvaior).您遇到的主要问题是您的递归案例不返回任何内容——它从递归调用中丢弃返回的值,然后从 function 的末尾脱落(返回垃圾——未定义的行为)。 You need to actually return the value returned by the recursive call:您需要实际返回递归调用返回的值:
return generateaRandomWord(currentVector);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.