0
我的程序使用ifstream()和getline()来解析一个文本文件到两个向量深的对象中。即矢量内的矢量。一旦文本文件加载完成,内部向量包含超过250000个字符串对象。txt文件解析C++进入矢量更有效
这是痛苦的缓慢。有没有比使用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;
}
显示您的代码。 250000的大小不够慢,所以肯定会出现一些问题。 –
看起来像这样:http://stackoverflow.com/questions/3002122/fastest-file-reading-in-c – granmirupa
尝试'const string&'而不是'string'。此外,“this->”没用(它不会让事情变慢,只是没用)。此外,你是否用所有优化标志进行编译? – user31264