So I am trying to modify this code of vectors into lists. I understand vectors but fairly new to lists. This is what I have tried so Far how can I fix this Please let me Know. Here is the original vector code:
void insertion_sort(std::vector <int> &num) {
int i, j, key;
bool insertionNeeded = false;
for (j = 1; j < num.size(); j++) {
key = num[j];
insertionNeeded = false;
for (i = j - 1; i >= 0; i--) { // larger values move right
if (key < num[i]) {
num[i + 1] = num[i];
insertionNeeded = true;
}
else
break;
}
if (insertionNeeded)
num[i + 1] = key; //Put key into its proper location
}
}
Here is the code I tried to convert to Lists: I am getting an error when I run it
void insertion_sort(list<int> &li) {
int i, j, key;
bool insertionNeeded = false;
list<int>::iterator itr = li.begin();
for (j = 1; j < li.size(); j++) {
advance(itr, j);
key = *itr;
insertionNeeded = false;
for (i = j - 1; i >= 0; i--) { // larger values move right
advance(itr, i);
if (key < i) {
advance(itr, i + 1);
int temp1 = *itr;
advance(itr, i);
int temp2 = *itr;
temp1 = temp2;
insertionNeeded = true;
}
else
break;
}
if (insertionNeeded)
advance(itr, i + 1);
*itr = key;
}
}
This is my quick answer. The test code is here.
Note that
std::advance
modifies its argument. OTOH,std::next
leaves its argument unmodified.