3

私は、英語の辞書 (昇順) を読み取り、さらに処理を行う C++ プログラムを作成しています。

最初のステップでは、すべてのコンテンツを 2D 配列に読み込むことにしました。

string dictionary[x][y];

ここでx、 は AZ を表すサイズ 26 のみで、変数yに関連する単語を保存します。x

しかし、サイズは予測できず、y可変であるため、これをどのように行うことができるかわかりません。

次に、 というコンテナのことを聞きましたvectorvector上記の設計を行うためにどのように使用できますか? たとえば、2D ベクターを使用し、最初の次元を使用して最初の文字を運び、2 番目の次元を単語を運ぶとしますか?

4

6 に答える 6

2

multimapcharを併用できますstring

例:

#include <iostream>
#include <map>
#include <fstream>
#include <string>

using namespace std;

multimap<char,string> dictionary;

void printLetter(char ch)
{
    for (auto it=dictionary.equal_range(ch).first; it!=dictionary.equal_range(ch).second; ++it)
    {
        cout << it->second << endl;
    }
}

int main()
{
    fstream file;
    file.open("file.txt");
    //Read the data from the file
    while(!file.eof())
    {
        string temp;
        file >> temp;
        dictionary.insert(pair<char,string>(temp[0],temp));
    }

    file.close();
    //Print all
    for(auto i: dictionary)
    {
        cout << i.first << ":" << i.second << endl;
    }
    //Print words starting with specific letter
    printLetter('A');

    return 0;
}
于 2013-03-30T15:31:27.880 に答える
2

質問に直接答えるには、次のようにします。

std::vector<string> dictionary[26];

dictionary[4](vector可変長配列のように) のstrings

しかし、ソートされた辞書を保存するためのより良い方法があります。単語を追加しない場合は、すべてを に入れ、std::vector<std::string>を使用して一度並べ替えることができますstd::sort(dictionary.begin(), dictionary.end())。または、単語を追加/削除し、並べ替えられたリストを常に保持する必要がある場合std::set<std::string>は、常に並べ替えられた を使用できます (単語を挿入すると、適切な場所に配置されます)

于 2013-03-30T15:33:16.003 に答える
1

Trie Data Structure を使用して辞書を格納する必要があります。 これは Trie の C 実装です。あなたは簡単にC ++に取り組むことができます

于 2013-06-10T08:16:47.237 に答える
0

ベクトルの配列を利用できます: std::vector<string> dictionary[26]. この背後にある考え方は、最初のものと同じです(std::vector::push_back()メソッドで行に単語を追加することを除いて;))

于 2013-03-30T15:31:57.640 に答える
0

辞書を入れておくことができます

 std::vector<std::pair< string,std::vector<string> > > 

各ベクトル要素がベクトル内の文字と単語のリストを含むように構造化します。

于 2013-03-30T15:33:29.083 に答える