Description
You are required to write one ( or more, maybe overload ) function templates to sort different kind of elements.
There are 2 or 3 arguments in the function. The first and the second arguments are iterators ( you can treat them as pointers ), stand for the beginning and the end positions of the sorted elements.
There may be a third argument, whitch is function comparing two elements.
If the function returns TRUE, it means that the first argument of the function should be in front of the second one in the sorted sequence.
Author:彭勃
Provided Codes
main.cpp
#include <vector>
#include <list>
#include <iostream>
#include "sort.h"
inline bool myCmp(const int & a, const int & b) {
return a > b;
}
int main() {
int n, * s, i;
std::vector<int> v;
std::list<int> l;
std::cin >> n;
s = new int[n];
for (i = 0; i < n; ++i) {
std::cin >> s[i];
v.push_back(s[i]);
l.push_back(s[i]);
}
mySort(v.begin(), v.end(), myCmp);
mySort(l.begin(), l.end());
mySort(s, s + n, myCmp);
for (i = 0; i < n - 1; ++i)
std::cout << v[i] << ' ';
std::cout << v.back() << std::endl;
for (std::list<int>::const_iterator i = l.begin(); i != l.end(); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
for (i = 0; i < n - 1; ++i)
std::cout << s[i] << ' ';
std::cout << s[n-1] << std::endl;
delete [] s;
return 0;
}
Submission
sort.h
#ifndef SORT_H
#define SORT_H
#include <algorithm>
using namespace std;
template <class RandomAccessIterator>
void mySort(RandomAccessIterator first, RandomAccessIterator last){
RandomAccessIterator iter=first;
int count=0;
while(iter!=last){
iter++;
count++;
}
int tem[count];
iter=first;
for(int i=0;i<count;i++)
tem[i]=*(iter++);
sort(tem,tem+count);
iter=first;
for(int i=0;i<count;i++)
*(iter++)=tem[i];
}
template <class RandomAccessIterator, class Compare>
void mySort(RandomAccessIterator first, RandomAccessIterator last, Compare comp){
sort(first,last,comp);
}
#endif