//定義類
class Hangman
{
private:
vector<string> dictionary; //stores all the words
vector<string> secretWord; //stores the secret word
vector<string> misses; //keeps record of wrong guesses
vector<string> displayVector; //Stores "_"
string originalWord; //stores a copy of secret word to display at the
end of game.
bool gameOver = false; //Flag to check if the player lost or
still in the game.
int totalAttempts;
public:
void selectRandWord();
};
//這是我遇到問題的函式。
void Hangman::selectRandWord()
{
secretWord.clear();
//word 是一個存盤隨機單詞的基本字串。讓我們說“你好世界”。
string word;
srand(time(NULL));
int random = (rand() % dictionary.size()) 1;
//我存盤一個從向量到單詞的隨機單詞。
word = dictionary[random];
transform(word.begin(), word.end(), word.begin(), ::tolower);
originalWord = word;
for (int index = 0; index < word.length(); index )
{
//這一行有錯誤:[Error] invalid user-defined conversion from 'char' to 'std::vectorstd::basic_string<char >::value_type&& {aka std::basic_string&&}' [-fpermissive]
//我想要做的是從單詞中取出每個字符(例如:“H”)并將其推回到向量字串secretWord中。
secretWord.push_back(word[index]);
}
}
uj5u.com熱心網友回復:
你secretWord現在是一個vector<string>型別,所以它可能是很多單詞的集合,我不確定這是否是你真正想要的名字。如果確實沒問題,并且您想將每個單個字符word作為單獨的stringin 存盤secretWord,那么您需要將push_backcall替換為emplace_backcall 因為另一個方法實際上一次執行兩件事:string從char傳遞給它的構造 a并附加string到容器的末尾,像這樣
secretWord.emplace_back(1, word[index]);
僅僅push_back失敗是因為它需要提供一個您vector商店型別的物件,因此您也可以通過string從您的明確構造 a來解決您的問題char:
secretWord.push_back(string(1, word[index]));
如果您對復制/移動細節感興趣,我建議您閱讀以下內容:放置回參考和推回參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369584.html
