これは必須条件です:新しい単語が出現するたびに、プログラムはその単語とその数を格納するために動的メモリからノードのインスタンスを割り当ててリンクリストそのリストは常にソートされます。遭遇した単語がすでにリストに存在する場合、その単語のカウントをインクリメントする必要があります。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++でオブジェクトを制御することがdiffirentようです。誰かが私のコードを調べて、より良い方法を提案できますか?
ありがとうございました。
"すべての権利" == "すべて間違っている"程度までは大丈夫です。少し違って言えば、それはひどい考えですが、それがあなたの課題に必要なものなら、あなたはそれにかなり執着しています。それは、不必要にゆっくりと機能します。 –