# HG changeset patch # User Markus Bröker # Date 1241195226 -7200 # Node ID 66f0244c28633c364f7d8fbf4e4950566e38e94f # Parent 91fbc3ea240b99e743282e3bbe76bed555ba4f6f nearest: more templates fun small improvements and a new template function committer: Markus Bröker diff --git a/nearest.cc b/nearest.cc --- a/nearest.cc +++ b/nearest.cc @@ -10,25 +10,22 @@ #include #include -using namespace std; - typedef short MYTYPE; namespace cute { template - Iter find (Iter begin, Iter end, const T& query) + Iter find (const Iter begin, const Iter end, const T& query) { Iter it; for (it = begin; it != end; it++) { - if (*it == query) + if (query == *it) return it; - } - return it; + } return it; } template - void nearest (Iter begin, Iter end, const T& query) + void nearest (const Iter begin, const Iter end, const T& query) { Iter it, current; @@ -37,17 +34,31 @@ return; while (current != end) { - cout << *current << endl; + std::cout << *current << std::endl; current++; } current = --it; do { - cout << *current << endl; + std::cout << *current << std::endl; } while ((current--) != begin); } -} + + template + 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) { @@ -58,12 +69,11 @@ 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 { + if (cin) { vec.push_back (value); lis.push_back (value); - } + } else + throw runtime_error ("BAD INPUT"); } sort (vec.begin (), vec.end ()); @@ -75,5 +85,7 @@ cute::nearest (vec.begin (), vec.end (), query); cute::nearest (lis.begin (), lis.end (), query); + cute::nearest (lis, query); + return 0; }