【问题标题】:C++ Length Error with bubble sort on a vector对向量进行冒泡排序的 C++ 长度错误
【发布时间】:2016-05-23 06:28:32
【问题描述】:

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

当我用一个常规的 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;
}

【问题讨论】:

  • bubbleSort(v.data(), 6); 你传递的是一个指向向量本身的指针,而不是它的内容。
  • 我建议让您的函数接受std::vector&lt;T&gt;&amp; 而不是T[]。我还建议使用std::swap 而不是自定义版本。
  • 仔细看看这个j+1。它会一直有效吗?检查 size==1。
  • 顺便说一句,我建议使用迭代器——这样你就可以传递从到到的范围,并让它们与其他算法轻松交互。

标签: c++ algorithm sorting vector bubble-sort


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    我还建议使用 std::swap 而不是自定义版本。 – Alex Zywicki 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

    【讨论】:

    • i 为零时,j 可以上升到a.size()-1。然后您参考a[j+1],它已结束。 (这个错误也存在于 OP 中)
    • 我编辑了我的回复,试图修复潜在的错误
    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多