0

so I am basically trying to make a function that sorts a vector of a struct called tasks based on the task's priority. My program crashes whenever the given vector has two items or more dunno what's wrong with my code help! n thanks!

void sort_tasks(std::vector<tasks> &tasks_list)
{
    if(!tasks_list.empty()){
        bool result = false;
        do
        {
            int counter = 0;
            for(std::vector<tasks>::iterator i = tasks_list.begin(); i != tasks_list.end(); i++)
            {
                if(counter < tasks_list.size())
                {
                    auto j = i++;
                    if(i->task_priority < j->task_priority) {
                        auto temp = *j;
                        *j = *i;
                        *i = temp;

                        if(!result) {
                            result = true;
                        }
                    }
                }
                counter++;
            }
        } while(result);

    }
}
4
  • 2
    Can you use std::sort? It will be much easier and more efficient than bubble sort. Commented Jun 9, 2020 at 10:59
  • 1
    And when you used your debugger to run your program, what did you see? This is precisely what a debugger is for. If you don't know how to use a debugger this is a good opportunity to learn how to use it to run your program one line at a time, monitor all variables and their values as they change, and analyse your program's logical execution flow. Knowing how to use a debugger is a required skill for every C++ developer, no exceptions. With your debugger's help you should be able to quickly find all bugs in this and all future programs you write, without having to ask anyone for help. Commented Jun 9, 2020 at 11:00
  • Learning how to debug your programs is a crucial skill to know what is going on during your program's run. Commented Jun 9, 2020 at 11:00
  • Think about when i is "pointing" to the last element in the vector. When you then do i++ where will it "point"? Commented Jun 9, 2020 at 11:00

1 Answer 1

1

Here auto j = i++; you don't check if i is tasks_list.end() after the increment.

You check it well in the for but you have to check it here too because you increment the iterator.

Sign up to request clarification or add additional context in comments.

1 Comment

that part of the code was supposed to be executed only if 'i' was inferior to the vector's size but ye since the index starts from 0 it has to be (i < vector.size() - 1). Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.