简体   繁体   中英

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. The data is given rather easily: (first column) int priority (second column) string task ie

orignal txt file

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). 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.

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.

Here is an example file that has 2 items.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM