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

猜你喜欢

转载自blog.csdn.net/z_j_q_/article/details/72811396