2017-04-23 10 views
0

私のプログラムは、ifstream()とgetline()を使用して、2つのベクトル深度のオブジェクトにテキストファイルを解析します。すなわちベクトル内部のベクトル。テキストファイルの読み込みが終了すると、内部ベクトルに250000を超える文字列オブジェクトが含まれます。ベクトルをより効率的にベクトル化するtxtファイル

これは非常に遅いです。 ifstream()とgetline()を使うよりも効率的なSTDの選択肢がありますか?

おかげ

UPDATE:

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <regex> 

using namespace std; 

class Word 
{ 
private: 
    string moniker = ""; 
    vector <string> definition; 
    string type = ""; 

public: 
    void setMoniker(string m) { this->moniker = m; } 
    void setDefinition(string d) { this->definition.push_back(d); } 
    void setType(string t) { this->type = t; } 
    int getDefinitionSize() { return this->definition.size(); } 

    string getMoniker() { return this->moniker; } 
    void printDefinition() 
    { 
     for (int i = 0; i < definition.size(); i++) 
     { 
      cout << definition[i] << endl; 
     } 

    } 


    string getType() { return this->type; } 
}; 

class Dictionary 
{ 
private: 
    vector<Word> Words; 

public: 
    void addWord(Word w) { this->Words.push_back(w); } 
    Word getWord(int i) { return this->Words[i]; } 
    int getTotalNumberOfWords() { return this->Words.size(); } 
    void loadDictionary(string f) 
    { 
     const regex _IS_DEF("[\.]|[\ ]"), 
      _IS_TYPE("^misc$|^n$|^adj$|^v$|^adv$|^prep$|^pn$|^n_and_v$"), 
      _IS_NEWLINE("\n"); 

     string line; 

     ifstream dict(f); 

     string m, t, d = ""; 

     while (dict.is_open()) 
     { 
      while (getline(dict, line)) 
      { 
       if (regex_search(line, _IS_DEF)) 
       { 
        d = line; 
       } 
       else if (regex_search(line, _IS_TYPE)) 
       { 
        t = line; 
       } 
       else if (!(line == "")) 
       { 
        m = line; 
       } 
       else 
       { 
        Word w; 
        w.setMoniker(m); 
        w.setType(t); 
        w.setDefinition(d); 
        this->addWord(w); 
       } 
      } 
      dict.close(); 
     } 
    } 
}; 



int main() 
{ 
    Dictionary dictionary; 
    dictionary.loadDictionary("dictionary.txt"); 
    return 0; 
} 
+2

コードを表示します。 250000は遅くなるほど大きくないので、いくつかの問題がなければなりません。 –

+0

次のようになります:http://stackoverflow.com/questions/3002122/fastest-file-reading-in-c – granmirupa

+0

'string'の代わりに' const string 'を試してみてください。さらに、 "this->"は役に立たない(物事を遅くすることはなく、役に立たない)。また、すべての最適化フラグを使用してコンパイルしますか? – user31264

答えて

0

あなたのメモリ割り当てを減らす必要があります。すべての内部ベクトルはnewdeleteを持っているので、ベクトルのベクトルを持つことは通常、良い考えではありません。

reserve()開始時にベクターに必要な要素のおおよその数。

std::stringを実際に抽出する必要がない場合は、fgets()を使用する必要があります。たとえば、オブジェクトがchar配列から解析できる場合は、それを行います。新しいバッファを作成するのではなく、毎回同じ文字列バッファに読み込むようにしてください。

さらに重要なのは、プロファイラを使用することです。

関連する問題