As a newbie I'm trying to implement a sorting function in C++, using the list-class. However, running the code I get the error that the list iterator is not incrementable... However it seems very unlikely as it should be incrementable!
code:
void shuffle (list<int> &list1)
{
list<int> smaller;
list<int> larger;
if (list1.size() > 1)
{
list<int>::iterator it;
//int it;
int x = list1.front();
for (it = list1.begin(); it != list1.end(); it++)
{
if(*it <= x)
{
smaller.push_front(*it);
list1.pop_front();
}
else
{
larger.push_back(*it);
list1.pop_front();
}
shuffle (smaller);
shuffle (larger);
}
}
else
{
print(smaller);
print(larger);
//cout << "No sorting needed! The list still looks like: ";
//print(list1);
}
print(smaller);
print(larger);
}
I implemented this function just in de CPP file, under the main.
Does anyone has any suggestions?
Your call to list1.pop_front() removes the element which the iterator is pointing to initially, invalidating it. And an invalid iterator can not be incremented. :)
It took a few minutes to find with the debugger. Just keep an eye on the value of 'it' as you step through the program. I don't know if you know how to use the debugger yet, but if not, do yourself a favor and learn it. It's an invaluable tool.
(By the way, in the future, please be explicit about whether the error occurs at compile-time or while running the program. Your question stated the error occurred when "compiling the program". I just edited the question for you, hope you don't mind. But it's an important distinction, and makes it harder to answer your question accurately)
I was also able to compile the posted code with VS2008 after I commented out the calls to print() and added the following to the beginning:
#include <list>
using namespace std;
This is my main:
> int _tmain(int argc, _TCHAR* argv[])
{
//DEFINE LIST
list <int> list1;
//FILL LIST
list1.push_front(5);
list1.push_front(2);
list1.push_front(1);
list1.push_front(9);
list1.push_front(12);
list1.push_front(3);
list1.push_front(4);
//PRINT LIST BEFORE SORTING
print(list1);
//SORT LIST
shuffle(list1);
//PRINT AFTER SORTING
system("pause");
return 0;
And the error message is just 1, namely if I debug it (press F5 in VC++ 2008) I get a pop-up that list iterator is not incrementable
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.