小程序编译出错(交换排序)

来源:百度知道 编辑:UC知道 时间:2024/06/16 10:43:44
#include<iostream>
using namespace std;

template<class T>
void swap(T& x,T& y)
{
T temp;
temp=x;
x=y;
y=temp;
}

template<class T>
void bubbleSort(T a[],int n)
{
int i=n-1,j,last;
while(i>0)
{
last=0;
for(j=0;j<i;++j)
{
if(a[j+1]<a[j])
{
swap(a[j],a[j+1]); //出错
last=j;
}
}
i=last;
}
}

int main()
{
int a[10]={90,1,0,33,13,4545,223,77,45,12};
bubbleSort(a,10); //出错
for(int i=0;i<10;++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
cin>>a[0];
}

#include<iostream>
using namespace std;

template<class T>
void myswap(T &x,T &y)
{
T temp;
temp=x;
x=y;
y=temp;
}

template<class T>
void bubbleSort(T a[],int n)
{
int i=n-1,j,last;
while(i>0)
{
last=0;
for(j=0;j<i;++j)
{
if(a[j+1]<a[j])
{
myswap(a[j],a[j+1]); //出错
last=j;
}
}
i=last;
}
}

int main()
{
int a[10]={90,1,0,33,13,4545,223,77,45,12};
bubbleSort(a,10); //出错
for(int i=0;i<10;++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
cin>>a[0];
return 0;
}

楼主啊,这里有个陷阱要注意啊,这个是书上的例子不好所导致的
因为标准库里也有swap()函数,所以调用的是标准库里的swap()
所以不能进行交换了,因此以后写程序不要使用和标准库重名的函数,因为这很容易让你会摸不着头脑

为什么非要用模板呢?直接用int不就行了