3

辞書を作りました。私の目標は、ユーザーに新しい単語を入力して定義してもらうことです。

「言葉の定義」の部分が下にあり、残りが下にあると思います。私が探しているものの例を以下に書きました。誰かにやってもらいたくありません。これを行う方法があるかどうか、またどこで詳細を学べるかを知りたいだけです。

現在、私はダミー用に C++ を使用しており、教師用には Sam の Teach Yourself を使用しています。

string newword
string word

cout << "Please enter a word" >> endl;
cin >> word;
if (word == newword)
{
    create string <newword>; // Which would make the following
                             // source code appear without
                             // actually typing anything new
                             // into the source code.
}  
string newword
string word
string word2 // which would make this happen

cout << "Please enter a word" >> endl;
cin >> word;
if (word == newword)
{
    create string <newword> 
}
4

2 に答える 2

3

std::mapまあ、それは辞書スタイルのコンテナなので、私は使用します。コンテナーはこのmapような状況に最適であり、他のデータと一致する一意のキーを提供できます。一般的な辞書には各単語に対して1 つのエントリしかないため、これは完璧です。

typedef を使用すると、名前で型を定義できます。ここでは、何度も入力std::map<std::string, std::string>する必要がないので便利です。が表示されるたびに想像してみてくださいDictionarystd::map<std::string, std::string>

// Map template requires 2 types, Key type and Value type.
// In our case, they are both strings.
typedef std::map<std::string, std::string> Dictionary;
Dictionary myDict;

次に、ユーザーにエントリを求めてから、エントリを定義するように求めます。

std::string word;
std::cout << "What word would you like added to the dictionary?" << std::endl;
std::cin >> word;

std::string definition;
std::cout << "Please define the word " << word << std::endl;
std::cin >> definitiion;

次のステップでは、単語とその定義を辞書に挿入するだけです。マップで演算子を使用し[]て、指定された key の既存のエントリを置き換えますword。まだ存在しない場合は、新しいエントリとして挿入されます。同じ名前の以前に定義された単語は、新しい定義を持つことに注意してください!

myDict[word] = definition;

これを実行すると、次のようなものが生成されます。

>> What word would you like added to the dictionary?
>> Map
>> Please define the word Map
>> Helps you find things

マップ内の定義へのアクセスは簡単になりました。

myDict["Map"]; // Retrieves the string "Helps you find things"
于 2012-09-19T02:37:20.310 に答える
1

編集:私の答えは、定義なしで単語のリストを作成する方法のみを示しています。うまくいけば、いくつかの精神的な扉が開かれますが、各単語に定義を付けるという主な目標を達成するには、Aestheteの回答mapが示すように、 a の代わりに aを使用する必要があります。vector

必要なのは、文字列のコレクションを含む変数です。最も使いやすく、最も一般的に使用されるのは、ベクターです。

// At the top of your program
#include <vector>

...

vector<string> words;

...

cout << "Please enter a word" << endl;
cin >> word;
words.push_back(word);     // This adds word to the end of the vector.

と呼ばれるベクトルがある場合、words次の構文を使用して (i+1) 番目の要素にアクセスできるという点で、ベクトルは配列と非常によく似た動作をしますwords[i]

cout << "The 3rd word is " << words[2] << endl;

2上記を、変数に依存するものを含む、他のより複雑な式に置き換えることができます。これにより、すべての単語をリストするなどのことができます。

for (int i = 0; i < words.size(); ++i) {
    cout << "Word " << (i + 1) << " is " << words[i] << endl;
}

于 2012-09-19T02:32:48.890 に答える