List iterator not dereferencable error

I know what causes this error but i dont know how to fix it without changing what im supposed to do in this function.
the error is in the line old=*it (I debugged the code and it gives me the error when i get to this line)
what i want to do is to add the course in order (for example if its number is 5 and i have 1 and 100 in the list, it must be added before the 100)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  Student::Result Student::registerToCourse(const Course& course){
	cout << "Registereing to Course" << endl;
	int old;
	std::list<int>::iterator it = listofcourses.begin();
	old = *it;
	//add course id to the list of course at the right place (in order)
	while (it != listofcourses.end() && *it > old) {
		old = *it;
		it++;
	}
	if (it == (it--))
	{
		cout << "you are already registered to this course! Cannot be registered to again."<<endl;
			return Already_Registered;
	}
	listofcourses.insert(it, course.getNumber());
	cout << "Registering to course done successfully" << endl;
	return Ok;
}


hope anyone can help. thanks in advance
it is invalid on line 5 and 11 if listofcourses is empty.

You may simply use sort for this:

http://www.cplusplus.com/reference/algorithm/sort/
You need to get the course number before the loop so you know where to place it.

I would go for std::lower_bound rather than a loop anyway:
http://www.cplusplus.com/reference/algorithm/lower_bound/
thanks. :)
Topic archived. No new replies allowed.