簡體   English   中英

在C ++中分割文本行的最有效方法是什么?

[英]What is the most efficient way to split a line of a text in C++?

我正在處理一些文本文件,其中我需要閱讀所有行,並且需要到達這些行中的字符串。 我使用了如下方法(假設每行有4個字符串):

string word1 , word2, word3, line;
while( getline( inputFile,line )){

    stringstream row(line);
    row>>word1>>word2>>word3>>word4;

}

但是,結果效率很低,我的程序運行得不太快。 如何改善方法? 提前致謝!

不要使用getline和字符串流使用讀取功能讀取大塊數據中的所有字符串

ifstream file ("file.txt", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
    file.seekg(0, ios::end);
    int block_size = file.tellg();
    char *contents = new char [block_size];
    file.seekg (0, ios::beg);
    file.read (contents, block_size);
    file.close();

    //... now deal with the string (I/O operations take more time once the entire 
    // file is in RAM it will be faster to operate on )

    delete [] contents;
}

如果文件大小超出了堆內存的限制,則必須讀取預定義的塊大小並對其進行操作,然后釋放內存並移至下一個塊

建議

我看到兩個變體。 我在該文件中比較了所有三個變體(您的和兩個地雷):

(bash)表示((i = 0; i <100000; ++ i)); 回顯“ $ i $ i $ i $ i”; 完成> test.txt

將test.txt放在tmpfs中。 所有計時以秒為單位。

您的變體:CPU時間0.130000,絕對時間0.135514

我的變體1:CPU時間0.060000,絕對時間0.062909,

我的變量2:CPU時間0.050000,絕對時間0.052963

1)“ C模式”:

//FILE *in  
char buf[1000];
buf[sizeof(buf) - 1] = '\0';
char w1[sizeof(buf)];
char w2[sizeof(buf)];
char w3[sizeof(buf)];
char w4[sizeof(buf)];
while (fgets(buf, sizeof(buf) - 1, in) != nullptr) {
    *w1 = *w2 = *w3 = *w4 = '\0';
    sscanf(buf, "%s %s %s %s", w1, w2, w3, w4);//here should be check for == 4
    //words.emplace_back(std::string(w1), std::string(w2), std::string(w3), std::string(w4));
}

2)“映射文件”:

//MapFile in;
const char *beg = in.begin();
const char *end = beg + file_size;
std::string w[4];
const char *ptr = beg;
bool eof = false;
do {
    for (int i = 0; i < 4; ++i) {
        const char *q = find_end_of_word(ptr, end);
        w[i].assign(ptr, q - ptr);
        if (q == end) {
            eof = true;
            break;
        }
        ptr = q;
        while (ptr != end && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n'))
            ++ptr;
        if (ptr == end) {
            eof = true;
            break;
        }
    }
    //words.emplace_back(w[0], w[1], w[2], w[3]);

// printf(“%s%s%s%s \\ n”,w [0] .c_str(),w [1] .c_str(),w [2] .c_str(),w [3] .c_str ()); } while(!eof);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM