[英]txt file parsing c++ in to vector more efficiently
我的程序使用ifstream()和getline()將文本文件解析為兩個向量深的對象。 即向量里面的向量。 文本文件加載完成后,內部向量包含超過250000個字符串對象。
這太慢了。 是否有一種STD替代方法比使用ifstream()和getline()更有效?
謝謝
更新:
#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;
}
您應該減少您的內存分配。 擁有向量的向量通常不是一個好主意,因為每個內部向量都執行其自己的new
和delete
。
您應該在一開始就reserve()
向量中所需的大致元素數量。
如果實際上不需要提取std::string
來完成工作,則應該使用fgets()
。 例如,如果可以從char
數組中解析對象,請執行此操作。 確保每次都讀取相同的字符串緩沖區,而不是創建新的緩沖區。
最重要的是,使用探查器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.