nearest.cc
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 27 Dec 2013 16:00:09 +0100
changeset 167 7c6b221900bf
parent 89 66f0244c2863
permissions -rw-r--r--
Proper Datatypes to leave the 80's

/**
 * I am experimenting with templates...
 *
 */

#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <iomanip>

typedef short MYTYPE;

namespace cute {
    template <typename Iter, typename T>
    Iter find (const Iter begin, const Iter end, const T& query)
    {
        Iter it;

        for (it = begin; it != end; it++) {
            if (query == *it)
                return it;
        } return it;
    }

    template <typename Iter, typename T>
    void nearest (const Iter begin, const Iter end, const T& query)
    {
        Iter it, current;

        current = it = cute::find (begin, end, query);
        if (current == end)
            return;

        while (current != end) {
            std::cout << *current << std::endl;
            current++;
        }

        current = --it;

        do {
            std::cout << *current << std::endl;
        } while ((current--) != begin);
    }

    template <class C, class T>
    typename C::iterator nearest (C& con, const T& query)
    {
        typename C::iterator it;

        for (it = con.begin (); it != con.end (); it++) {
            if (query == *it)
                return it;
        }
        return it;
    }
};

using namespace std;

int main (int argc, char **argv)
{
    MYTYPE value, query;
    vector <MYTYPE> vec;
    list <MYTYPE> lis;

    for (int i = 0; i < 10; i++) {
        cout << "[" << std::setw (2) << i << "] Enter a value: ";
        cin >> value;
        if (cin) {
            vec.push_back (value);
            lis.push_back (value);
        } else
            throw runtime_error ("BAD INPUT");
    }

    sort (vec.begin (), vec.end ());
    lis.sort ();

    cout << "Enter a value to search: ";
    cin >> query;

    cute::nearest (vec.begin (), vec.end (), query);
    cute::nearest (lis.begin (), lis.end (), query);

    cute::nearest (lis, query);

    return 0;
}