C++ 矢量上气泡排序的长度错误

C++ Length Error with bubble sort on a vector

本文关键字:错误 排序 气泡 C++      更新时间:2023-10-16

我正在尝试编写一个模板函数的气泡排序实现。

当我使用常规 ol' 数组测试此算法时,它似乎工作正常。我得到正确的输出。

但是,当我使用向量测试它时,我得到了一个length_error异常,我不太确定为什么。

template<class T>
void swap_right(T a[], int index)
{
    T temp = a[index];
    a[index] = a[index+1];
    a[index+1] = temp;
}
template<class T>
void bubbleSort(T a[], int size)
{
    for(int i = 0; i < size; ++i)
    {
        for(int j = 0; j < (size-i); ++j)
        {
            if(a[j] > a[j+1])
            {
                swap_right(a, j);
            }
        }
    }
}
#include <iostream>
#include <vector>
int main(int argc, const char * argv[])
{
    std::vector<int> v {9, 5, 3, 7, 4, 1};
    bubbleSort(&v, 6);
    for(int i = 0; i < 6; ++i)
    {
        std::cout << v[i] << std::endl;
    }
    return 0;
}

你传递一个指向向量的指针,这基本上意味着你尝试对向量数组进行排序,这是不正确的,会导致未定义的行为

相反,您应该将向量的内容传递给排序函数,例如使用 data() 成员函数:

bubbleSort(v.data(), v.size());

我建议让你的函数接受std::vector&而不是T[]。

我还建议使用 std::swap 而不是自定义版本。 – 亚历克斯·齐维基 3分钟前 编辑

#include <iostream>
#include <vector>

template<class T>
void bubbleSort(std::vector<T>& a)
{
    for(unsigned i = 0; i < a.size(); ++i)
    {
        for(unsigned  j = 0; j < (a.size()-i)-1; ++j)
        {
            if(a[j] > a[j+1])
            {
                std::swap(a[j],a[j+1]);
            }
        }
    }
}

int main(int argc, const char * argv[])
{
    std::vector<int> v {9, 5, 3, 7, 4, 1};
    bubbleSort(v);
    for(unsigned i = 0; i < v.size(); ++i)
    {
        std::cout << v[i] << std::endl;
    }
    return 0;
}

现场演示:http://coliru.stacked-crooked.com/a/e22fe55a38425870

结果是:

1 3 4 5 7 9