nearest: more templates fun
authorMarkus Bröker <mbroeker@largo.dyndns.tv>
Fri, 01 May 2009 18:27:06 +0200
changeset 89 66f0244c2863
parent 88 91fbc3ea240b
child 90 d494813f9e5b
nearest: more templates fun small improvements and a new template function committer: Markus Bröker <mbroeker@largo.homelinux.org>
nearest.cc
--- a/nearest.cc
+++ b/nearest.cc
@@ -10,25 +10,22 @@
 #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 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 <typename Iter, typename T>
-    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 <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)
 {
@@ -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;
 }