2012-04-22 29 views
0

這是要求:遇到新字時,程序應該從動態內存中分配一個節點實例以包含該字及其計數並將其插入鏈表以便列表總是排序。如果遇到的單詞已經存在於列表中,那麼該單詞的計數應該增加。C++中來自文件輸入的不同字和計數

我在任何地方都搜索過,正確的解決方案是使用std :: map,但我不想使用它,因爲迄今爲止我還沒有知道。使用List或Vector並創建一個結構或類來操縱每個節點是否正常?

這是我正確的代碼

class Node { 
string word; 
int count; 

public: 
    Node() { 
     word = ""; 
     count = 1; 
    } 
    Node(const Node &other) : word(other.word), count(other.count) { 
     // copy constructor 
    } 
    ~Node() {} // Destructor 

    void printWord() const { 
     cout << count << " " << word << endl; 
    } 
    void loadWord(ifstream &fin) { 
     fin >> word; 
    } 
    void setWord(const string &word) { 
     this->word = word; 
    } 
    const string& getWord() const { 
     return word; 
    } 
    void incrementCount() { 
     count++; 
    } 
}; 

void load(list<Node> &nodes, const char *file); 
void print(const list<Node> &nodes); 
bool isExist(const list<Node> &nodes, const string &word, Node &node); 
void error(const string &message, const char *file); 
const Node& getNode(const list<Node> &nodes, const string &word); 

int main(int argc, char *argv[]) { 

    list<Node> nodes; 

    if (argc != 2) { 
     cout << "Error syntax : require an input file\n"; 
     return 0; 
    } 
    load(nodes, argv[1]); 
    print(nodes); 

    return 0; 
} 

void print(const list<Node> &nodes) { 

    list<Node>::const_iterator itr; 

    for (itr = nodes.begin(); itr != nodes.end(); itr++) { 
     itr->printWord(); 
    } 
cout << '\n'; 
} 

void load(list<Node> &nodes, const char *file) { 

    ifstream fin; 
    Node node; 
    string temp; 

fin.open(file); 

if (!fin) 
    error("Cannot open file ", file); // exit 

while (!fin.eof()) { 
    if (fin.good()) { 
     fin >> temp; 
     if (!isExist(nodes, temp, node)) { 
      node.setWord(temp); 
      nodes.push_back(node); 
     } else { 
      // increase word count here 
     } 

    } else if (!fin.eof()) 
     error("Unable to read data from ", file); 
} 
fin.close(); 
} 

bool isExist(const list<Node> &nodes, const string &word, Node &node) { 
list<Node>::const_iterator itr; 
for (itr = nodes.begin(); itr != nodes.end(); itr++) { 
    if(word.compare(itr->getWord()) == 0) { 
     return true; 
    } 
} 
return false; 
} 

const Node& getNode(const list<Node> &nodes, const string &word) { 
    list<Node>::const_iterator itr; 
    for (itr = nodes.begin(); itr != nodes.end(); itr++) { 
     if(word.compare(itr->getWord()) == 0) { 
      return *itr; 
     } 
    } 
    return NULL; // This is fail what should I do to return a NULL value when not found 
} 

void error(const string &message, const char *file) { 
cerr << message << file << '\n'; 
exit(0); 
} 

的代碼不工作,我只是試圖生成我的解決方案通過將我的Java知識來解決這個問題,但似乎向度來控制對象在C++。有人可以檢查我的代碼併爲我提供更好的方法嗎?

謝謝。

+1

「好吧」==「全錯」。說得有點不同,這是一個可怕的想法,但如果這是你的任務需要,那麼你幾乎堅持下去。它會工作,只是不必要的慢。 – 2012-04-22 05:38:00

回答

0

不,這不是練習向量和列表的最佳任務。你真的必須看看std :: map文檔,並寫出3行高效,漂亮的代碼。 你爲什麼不應用你的TreeMap Java知識?

相關問題