8. Sablonok

Czirkos Zoltán · 2019.02.27.

Vektor osztálysablon és Rendezés függvénysablon

1. Vektor osztálysablon

#include <iostream>

template <typename TIP, size_t D>
class Vektor {
    private:
        TIP koord[D];       // TIP(), ~TIP()
    public:
        Vektor() {
            for (size_t i = 0; i < D; ++i)
                koord[i] = 0;       // TIP = int,   TIP(int)
        }
        TIP & operator[] (size_t i) {
            return koord[i];
        }
        TIP const & operator[] (size_t i) const {
            return koord[i];
        }
        Vektor operator+ (Vektor const & rhs) const;
};

template <typename TIP, size_t D>
Vektor<TIP,D> Vektor<TIP,D>::operator+ (Vektor<TIP,D> const & rhs) const {
    Vektor osszeg;
    for (size_t i = 0; i < D; ++i)
        osszeg[i] = (*this)[i] + rhs[i];        // TIP+TIP, TIP = TIP
    return osszeg;      // TIP(TIP const&)
}


template <typename TIP, size_t D>
std::ostream & operator<< (std::ostream & os, Vektor<TIP,D> const & v) {
    os << '(';
    for (size_t i = 0; i < D-1; ++i)
        os << v[i] << ';';      // os << TIP
    os << v[D-1] << ')';
    return os;
}

int main() {
    Vektor<double, 2> v1, v2;

    v1[0] = 4.3; v1[1] = 5;
    v2[0] = 9.8;

    Vektor<double, 2> v3 = v1+v2;
    std::cout << v3;  // template parameter deduction

    return 0;
}

2. Rendezés függvénysablon

#include <iostream>
#include <string>

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

template <typename T>
void rendez(T* tomb, size_t n) {
    for (size_t i = 0; i < n-1; i++) {
        size_t min = i;
        for (size_t j = i+1; j < n; j++) {
            if (tomb[j] < tomb[min])
                min = j;
        }
        csere(tomb[i], tomb[min]);
    }
}

int main() {
    std::string tomb[5] = { "alma", "korte", "barack", "dinnye", "papaja" };
    rendez(tomb, 5);

    for (size_t i = 0; i < 5; ++i)
        std::cout << tomb[i] << ", ";
    std::cout << std::endl;

    return 0;
}