C++ C++;向量上气泡排序的长度错误
我正在尝试编写一个冒泡排序的实现,它是一个模板函数 当我用一个普通的ol'数组测试这个算法时,它似乎工作得很好。我得到了正确的输出 然而,当我用一个向量测试它时,我得到了一个length_错误异常,我不确定为什么C++ C++;向量上气泡排序的长度错误,c++,algorithm,sorting,vector,bubble-sort,C++,Algorithm,Sorting,Vector,Bubble Sort,我正在尝试编写一个冒泡排序的实现,它是一个模板函数 当我用一个普通的ol'数组测试这个算法时,它似乎工作得很好。我得到了正确的输出 然而,当我用一个向量测试它时,我得到了一个length_错误异常,我不确定为什么 template<class T> void swap_right(T a[], int index) { T temp = a[index]; a[index] = a[index+1]; a[index+1] = temp; } templat
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;
}
模板
无效交换权(TA[],整数索引)
{
温度=a[指数];
a[索引]=a[索引+1];
a[指数+1]=温度;
}
模板
void bubbleSort(T a[],整数大小)
{
对于(int i=0;ia[j+1])
{
互换权(a,j);
}
}
}
}
#包括
#包括
int main(int argc,const char*argv[]
{
std::向量v{9,5,3,7,4,1};
气泡运动试验(6);
对于(int i=0;i<6;++i)
{
std::cout传递一个指向向量的指针,这基本上意味着尝试对向量数组进行排序,这是不正确的,将导致未定义的行为
相反,您应该将向量的内容传递给排序函数,例如使用成员函数:
bubbleSort(v.data(), v.size());
我建议让函数接受std::vector&而不是T[]
我还建议使用std::swap而不是定制版本
#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;
}
#包括
#包括
模板
void bubbleSort(标准::向量&a)
{
for(无符号i=0;ia[j+1])
{
互换(a[j],a[j+1]);
}
}
}
}
int main(int argc,const char*argv[]
{
std::向量v{9,5,3,7,4,1};
泡泡运动(v);
for(无符号i=0;i std::coutbubbleSort(v.data(),6);
您传递的是指向向量本身的指针,而不是它的内容。我建议让您的函数接受std::vector&
而不是T[]
。我还建议使用std::swap
而不是自定义版本。仔细研究一下这个j+1
。它会一直工作吗?检查大小==1。另外,我建议使用迭代器-这样你就能够从一个范围传递到另一个范围,并让它们与其他算法轻松交互。当I
被禁用时o、 j
可以上升到a.size()-1
。然后您可以参考结尾处的a[j+1]
。(此错误也出现在OP中)我编辑了我的响应,试图修复潜在的错误