简体   繁体   English

在 C++ 中按优先级升序对带有 int 和 string 的 txt 文件进行排序

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

What i want to do is I want to create a function in C++ to sort a txt file.我想做的是我想在 C++ 中创建一个 function来对 txt 文件进行排序。 The data is given rather easily: (first column) int priority (second column) string task ie数据很容易给出:(第一列)int优先级(第二列)字符串任务,即

orignal txt file原始的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

what i want it to be我想要什么

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

I have tried in several ways, but none of them works.我已经尝试了几种方法,但它们都不起作用。 I want it to be sorted in increasing order of priority (0 being the least priority).我希望它按优先级升序排序(0 是最低优先级)。 if two or more tasks have same priority then it should be sorted in order of occurrence.如果两个或多个任务具有相同的优先级,则应按发生顺序对其进行排序。 Each task occupies a single line in this file.每个任务在此文件中占一行。 Each line in the file should be in this format:文件中的每一行都应采用以下格式:

p task任务

where p is the priority ( priority will be a number) and task is the task description.其中 p 是优先级(priority 将是一个数字),task 是任务描述。

Priority denotes how important a task is, if it is a high priority task, it should be completed earlier.优先级表示一个任务的重要性,如果是高优先级的任务,就应该早点完成。 Priority is denoted using an integer, the lower the number, the higher the priority.优先级使用 integer 表示,数字越小,优先级越高。

Here is an example file that has 2 items.这是一个包含 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