I cant figure out the error. please help?

#include <iostream>
using namespace std;
template <class T>
void swap(T& a, T& b)
{T temp=a; a=b; b=temp; }
int main ()
{
int a[5]={4,3,2,1,0};
for(int i=1;i<5;i++)
{ for(int j=0;j<5-i;j++)
if( a[j] > a[j+1]) swap<int,int>(a[j],a[j+1]);
for(int k=0;k<5;k++)
cout<<a[k]<<" ";
cout<<endl; }
return 0;
}
Hard to tell without saying what the actual error is.

At a glance, I'd imagine it's this line:
if( a[j] > a[j+1]) swap<int,int>(a[j],a[j+1]);

In the fifth iteration of your loop (where j will be equal to 4) you're access a[j+1], which in this iteration is a[5].

Given that the array a has five elements, the highest element is a[4]. By trying to access a[5] you're trying to access an index that is out of the array bounds.
Are you getting a compile time error, or a run time error?

I'm guessing you're getting a compile time error on the following line:
 
if( a[j] > a[j+1]) swap<int,int>(a[j],a[j+1]);


You've declared swap as a templated function taking one type,
1
2
template <class T>
void swap(T& a, T& b)

therefore the line should be:
 
if( a[j] > a[j+1]) swap<int>(a[j],a[j+1]);


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
Topic archived. No new replies allowed.