c++ 排序算法适用于C数组,但不适用于std::span [closed]

lymnna71  于 2023-05-24  发布在  其他
关注(0)|答案(1)|浏览(165)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
2天前关闭。
Improve this question
这个问题发生在我使用insertion_sort算法时。我尝试实现C++20的std::span版本,但它抛出**“std::span index out of range”,因此我将其转换为“C-array”**,相同的代码工作正常。我不知道问题出在哪里。P.S我的平台是windows10,我使用的是VisualStudio 2022
这是std::span版本。

template <typename Ty>
void insertion_sort(std::span<Ty> arr) {
    long long size = arr.size();
    // From the 2nd element to the nth element
    for (long long i = 1; i < size; ++i) {
        Ty key = arr[i];
        long long j = i - 1;
        // Until the first element.
        for (; arr[j] > key && j >= 0; --j)
            arr[j + 1] = arr[j];
        // Place key into the right position.
        arr[j + 1] = key;
    }
}

但是,如果我将std::span改为**C-array,就像下面这样,它可以正常工作。

template <typename Ty>
void insertion_sort(Ty* arr, std::size_t size) {
    // From the 2nd element to the nth element
    for (long long i = 1; i < size; ++i) {
        Ty key = arr[i];
        long long j = i - 1;
        // Until the first element.
        for (; arr[j] > key && j >= 0; --j)
            arr[j + 1] = arr[j];
        // Place key into the right position.
        arr[j + 1] = key;
    }
}

如果有人能帮我解决这个问题,我会很高兴!

nzk0hqpo

nzk0hqpo1#

for循环中的条件

for (; arr[j] > key && j >= 0; --j)
        arr[j + 1] = arr[j];

错误。您需要交换逻辑AND运算符的操作数

for (; j >= 0 && arr[j] > key; --j)
        arr[j + 1] = arr[j];

否则,表达式arr[j]的索引可以等于-1

相关问题