繁体   English   中英

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

[英]C++ Length Error with bubble sort on a vector

我正在尝试编写作为模板函数的冒泡排序的实现。

当我用常规的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而不是自定义版本。 – 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM