I am trying to write code that will alphabetize strings in a linked list. Here is what I have written:
void main() {
list<string> myList;
list<string>::iterator pos;
string newData;
myList.push_back("Anna");
pos = myList.begin();
for (int i = 0; i < 5; i++){
cin >> newData;
while(newData > *pos)
pos++;
myList.insert(pos, newData);
}
system("pause");
}
This code compiles fine but I get an error that the list iterator is not dereferenceable when I run it.
I am very new with linked lists and iterators so I really don’t know how to fix it. Any help would be greatly appreciated!
The problem is in this cycle:
Depending on your input, you might keep increasing
posuntil you reach the end of the list. At that point, dereferencing it when checking the condition of yourwhileloop causes Undefined Behavior.To fix your program, rewrite your cycle as follows:
P.S.: Also notice, that you most likely want to move the
pos = myList.begin();statement inside theforloop, if your intention is to insert the items in inverse lexicographic order (as it seems to be).