簡體   English   中英

在 C++ 中按優先級升序對帶有 int 和 string 的 txt 文件進行排序

[英]Sort a txt file with int and string in ascending order of priority in C++

我想做的是我想在 C++ 中創建一個 function來對 txt 文件進行排序。 數據很容易給出:(第一列)int優先級(第二列)字符串任務,即

原始的txt文件

4 make coffee
3 make charts
6 prepare notes 
2 do homework
6 go for walk
0 prepare prenentation
2 prepare essay 
1 lorem ipsum

我想要什么

0 prepare prenentation
1 lorem ipsum
2 do homework
2 prepare essay 
3 make charts
4 make coffee
6 prepare notes 
6 go for walk

我已經嘗試了幾種方法,但它們都不起作用。 我希望它按優先級升序排序(0 是最低優先級)。 如果兩個或多個任務具有相同的優先級,則應按發生順序對其進行排序。 每個任務在此文件中占一行。 文件中的每一行都應采用以下格式:

任務

其中 p 是優先級(priority 將是一個數字),task 是任務描述。

優先級表示一個任務的重要性,如果是高優先級的任務,就應該早點完成。 優先級使用 integer 表示,數字越小,優先級越高。

這是一個包含 2 個項目的示例文件。

1 Buy milk
2 Complete the project
void sort_file()
{
    vector <string> task_t;
    fstream newfile;
    newfile.open("task.txt",ios::in); 
    if (newfile.is_open())
        {   
            string tp;
            while(getline(newfile, tp)) 
            {
                task_t.push_back(tp);
            }
            newfile.close(); 
        }
    std::sort(std::begin(task_t), std::end(task_t), [](std::string const& a, std::string const& b)
    {
        return std::lexicographical_compare(std::begin(a), std::begin(a) + 1, std::begin(b), std::begin(b) + 1);
    });
    std::ofstream outFile("task.txt");
    for (const auto &e : task_t)
        outFile << e << "\n";
    outFile.close();
}

暫無
暫無

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

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