递归地使用列表STL进行插入排序

Insertion sort using a list STL recursively

所以我正在尝试将这段向量代码修改为列表。我了解向量,但对列表还很陌生。到目前为止,这是我尝试过的方法我该如何解决这个问题请告诉我。 这是原始矢量代码:

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
}
}

这是我尝试转换为列表的代码: 当我 运行 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;
}
}

这是我的快速回答。 测试代码为here.

注意 std::advance 修改了它的参数。 OTOH,std::next 保留其论点不变。

void insertion_sort(std::list<int> &li)
{
    for (auto j = 1U; j < li.size(); ++j) 
    {
        auto itr = li.begin();
        std::advance(itr, j);
        const auto key = *itr;

        for (auto i = j; i > 0U; --i) // i is just a counter.
        {        
            std::advance(itr, -1);

            if (key < *itr) // larger values move right
            {
                const int temp = *itr;
                *itr = key;
                *std::next(itr) = temp;        
            }
            else{            
                break;
            }
        }
    }
}