Вот что у меня есть. Теперь проблема заключается в чтении и вставке строк слов, которые у меня есть в текстовом файле с именем «word.txt» в trie tree. Я использовал «недействительным Init()» функции, чтобы проверить, что функции дерева и он, но с помощью текстового файла, то где я не знаю, какЧтение текстового файла
любая идея пожалуйста
#include <iostream>
using namespace std;
#include <fstream>
#include <iomanip>
#include <string>
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
value = 0;
for (int i=0;i<26;i++){
children[i] = NULL;
}
}
int value;
TrieNode* children[26];
};
class Trie {
private:
TrieNode*root;
int count;
public:
Trie() {
root = new TrieNode();
count = 0;
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p = root;
long int len = s.size();
for (int i=0;i<len;i++){
int index = s[i] - 'a';
if (! p->children[index]){
p->children[index] = new TrieNode();
}
p = p->children[index];
}
count++;
p->value = count;
}
// Returns if the word is in the trie.
// -1 if not in trie and not prefix of anything in trie
// 0 if not in trie but is a prefix of something in trie
// 1 if in trie
int search(string key) {
TrieNode *p = root;
long int lenght = key.size();
for (int i=0;i<lenght;i++){
int index = key[i] - 'a';
if (p->children[index]){
p = p->children[index];
}
else{
return -1;
}
}
if (p->value!=0){
return 1;
}
else{
return 0;
}
}
};
//Game class using a tree
class GhostGame{
private:
string row;
ifstream fin;
string wordSoFar = "";
string Player1,Player2;
Trie Tree;
public:
void ReadFile(){
ifstream fin("word.txt");
while (!fin.eof()) { // read file till the end
fin>>row;
getline(fin,row);
cout << row << endl;
Tree.insert(row);
}
//fin.close();
}
void init(){
Tree.insert("ab");
Tree.insert("acd");
}
//start menu
void StartGame(){
init();
cout<<"========================="<<endl;
cout<<"Welcome to Ghost Game"<<endl;
cout<<"========================="<<endl;
//ReadFile();
while(Tree.search(wordSoFar)!=1){
cout<< "Player 1 Insert a letter => ";
cin>> Player1;
cout<<setw(60)<<"now = ["<< wordSoFar <<"]"<<endl;
wordSoFar +=Player1;
if(Tree.search(wordSoFar)==1){
cout<< "Player 2 Wins "<<endl;
break;
}
cout<< "Player 2 Insert a letter => ";
cin>>Player2;
cout<<setw(60)<<"now = ["<< wordSoFar<<"]"<<endl;
wordSoFar += Player2;
if(Tree.search(wordSoFar)==1){
cout<< "Player 1 Wins "<<endl;
break;
}
}
}};
// main driver
int main()
{
GhostGame G1;
G1.StartGame();
return 0;
}
....... Что ты уже испробовал? Где вы раньше искали? Этот сайт не для того, чтобы творить мысли для вас ... – itmuckel
Вы просите людей делать свою работу, а не помогать вам. Вам нужно сказать, что вы пытались не просто «СДЕЛАЙТЕ ЭТО ДЛЯ МЕНЯ» – kemis
Существует тип дерева, имя которого я забыл, которое создано для такого поиска. – user4581301