[英]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.