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;
}

Standard Answer

sort.h

#ifndef __SORT_H__
#define __SORT_H__

#include <iterator>

template<typename T>
void mySwap(T & a, T & b) {
    T t = a;
    a = b;
    b = t;
}

template<typename Iterator>
void mySort(Iterator begin, Iterator end) {
    Iterator i, j;
    for (i = begin; i != end; ++i) {
        j = i;
        for (++j; j != end; ++j)
            if (*j < *i)
                mySwap(*j, *i);
    }
}

template<typename Iterator, typename Comp>
void mySort(Iterator begin, Iterator end, Comp cmp) {
    Iterator i, j;
    for (i = begin; i != end; ++i) {
        j = i;
        for (++j; j != end; ++j)
            if (cmp(*j, *i))
                mySwap(*j, *i);
    }
}

#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值