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 而不是自定义版本。 – 亚历克斯·齐维基 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
相关文章:
- C++选择排序算法中的逻辑错误
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 对单向链表进行排序时出现运行时错误
- 无法在我的堆排序代码中找到错误.无法正确执行.C++
- 在气泡排序程序中未声明错误功能
- 仅在大型阵列上出现合并排序分段错误
- 分段 排序函数实现中的错误
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 字符串上的合并排序上的 Seg 错误
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- C++为什么我的指针选择排序中存在分段错误?
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 尝试按值对地图进行排序,但出现错误
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 合并排序:分段错误核心转储
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 合并排序中的错误计数:计数反转
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- C++中的错误排序算法