2736 FunctionTemplate(eden)

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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值