View Single Post
Old Jan 22nd, 2006, 1:43 PM   #2
Cache
Hobbyist
 
Join Date: Sep 2005
Posts: 261
Rep Power: 4 Cache is on a distinguished road
From 'stl_functions.h' which is uses the 'std' namespace:

/// One of the @link s20_3_3_comparisons comparison functors@endlink.
  template <class _Tp>
	struct greater : public binary_function<_Tp, _Tp, bool>
	{
	  bool
	  operator()(const _Tp& __x, const _Tp& __y) const
	  { return __x > __y; }
	};
That's conflicting with your 'greater' template function.

You can either scrap the 'using namespace std' - and go for std::string (or whatever), or make your own namespace:

namespace MySpace
{
   template<class T>
   int greater(T a, T b){return(a>b);}
   int greater(char *a, char *b){return strcmp(a,b)>0;}
}

template <class T>
void sort(T p[], int size){
   
	int i,k;
	for(k=1;k<size;k++)
		for(i=0;i<size-k;i++)
			if (MySpace::greater(p[i],p[i+1])>0){
				swap(p[i],p[i+1]);
			}
}

That still leaves: "call of overloaded `swap(int&, int&)' is ambiguous", though. I haven't messed with templates enough (yet) to suggest anything for that.

EDIT: It seems to work when the whole thing is namespaced up:

#include <iostream>
#include <string>
using namespace std;

namespace MySpace
{

template<class T>
void set(T p[], int num, char *name){
	int i;
	for(i=0; i<num; i++){
		cout << name << "[" << i << "]=";
		cin >> p[i];
	}
}

template<class T>
void show(T p[], int num, char *name){
	int i;
	for(i=0; i<num; i++){
		cout << name << "[" << i << "]=" << p[i] << "\n";
	}
}


   template<class T>
   int greater(T a, T b){return(a>b);}
   int greater(char *a, char *b){return strcmp(a,b)>0;}


template<class T>
void swap(T &a, T &b){
	T temp = a;
	a = b;
	b = temp;
}
void swap(char *a, char *b){
	char temp[20];
	strcpy(temp, a);
	strcpy(a,b);
	strcpy(b,temp);
}

template <class T>
void sort(T p[], int size){
   
	int i,k;
	for(k=1;k<size;k++)
		for(i=0;i<size-k;i++)
			if (greater(p[i],p[i+1])>0){
				swap(p[i],p[i+1]);
			}
}
}


int main(){
	char names[4][21]; int n=4;
	MySpace::set(names,n,"names");
	cout<<"\nunsorted names a\n";
	MySpace::show(names,n,"names");
	MySpace::sort(names,n); 
	cout<<"\nsorted names\n"; 
	MySpace::show(names,n,"names");
	int  numbers[4];
	MySpace::set(numbers,3,"numbers"); 
	cout<<"\nunsorted numbers b\n";
	MySpace::show(numbers,3,"numbers");
	MySpace::sort(numbers,3);
	cout<<"\nsorted numbers\n"; 
	MySpace::show(numbers,3,"numbers");
	
}

Last edited by Cache; Jan 22nd, 2006 at 1:53 PM.
Cache is offline   Reply With Quote