TXT 文件更有效地将 C++ 解析为矢量

txt file parsing c++ in to vector more efficiently

本文关键字:C++ 文件 有效地 TXT      更新时间:2023-10-16

我的程序使用 ifstream() 和 getline() 将文本文件解析为两个向量深度的对象,即向量内的向量。文本文件加载完成后,内部向量包含超过 250000 个字符串对象。

这是非常缓慢的。有没有比使用 ifstream() 和 getline() 更有效的 STD 替代方案?

谢谢

更新:

#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;
}

您应该减少内存分配。 拥有向量向量通常不是一个好主意,因为每个内部向量都有自己的newdelete

您应该在开始时reserve()向量中所需的元素的大致数量。

如果您实际上不需要提取std::string来完成工作,则应使用fgets()。 例如,如果可以从char数组中解析对象,请执行此操作。 确保每次都读入相同的字符串缓冲区,而不是创建新的缓冲区。

最重要的是,使用探查器。