下面是以冒泡排序算法为例:
#include<iostream>
#include<vector>
#include<list>
#include<functional>
#include<algorithm>
using namespace std;
template<typename T>
class Greater
{
public:
bool operator()(const T& lhs, const T& rhs)
{
return lhs < rhs;
}
};
template<typename T>
class Less
{
public:
bool operator()(const T& lhs, const T& rhs)
{
return lhs > rhs;
}
};
template<typename Iterator,typename Compare>
void Sort(Iterator first,Iterator last,Compare& cmp)
{
Iterator i=first;
Iterator j=first;
int k=0;
for(i,k=0;i<last-1;++k,++i)
{
for(j=first;j<last-1-k;++j)
{
if(cmp(*j,*(j+1)))
{
typename Iterator::value_type tmp=*j;
*j=*(j+1);
*(j+1)=tmp;
}
}
}
}
template<typename Container>
void Show(Container& con)
{
Container::iterator it = con.begin();
for (it; it != con.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
int arr[] = { 2, 16, 3, 3, 33, 4, 3 };
int len = sizeof(arr) / sizeof(arr[0]);
vector<int> vec(arr, arr+len);
Sort(vec.begin(), vec.end(), Greater<int>());
Show(vec);
return 0;
}