這是我到目前爲止。現在我遇到的問題是在我的名爲「word.txt」的文本文件中讀入並插入單詞串到樹結構樹中。我用「無效的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