nearest.cc
author Markus Bröker <mbroeker@largo.dyndns.tv>
Thu, 30 Apr 2009 23:38:48 +0200
changeset 88 91fbc3ea240b
child 89 66f0244c2863
permissions -rw-r--r--
how to use templates We read 10 numbers from stdin and print the nearest values of a query. committer: Markus Bröker <mbroeker@largo.homelinux.org>

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

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

using namespace std;

typedef short MYTYPE;

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

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

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

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

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

        current = --it;

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

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)
            throw std::runtime_error ("BAD_INPUT");
        else {
            vec.push_back (value);
            lis.push_back (value);
        }
    }

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

    return 0;
}