txt文件将c ++更有效地解析为向量

txt file parsing c++ in to vector more efficiently

我的程序使用 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 数组中解析出来,那么就这样做。确保每次都读入相同的字符串缓冲区,而不是创建新的缓冲区。

最重要的是,使用分析器。