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>
--- a/Makefile
+++ b/Makefile
@@ -65,6 +65,7 @@
TARGET += clplaner
TARGET += daemon
TARGET += numbers
+TARGET += nearest
.SUFFIXES: .c .cc .asm
@@ -312,6 +313,10 @@
@echo Linking $<...
@$(CC) -Wall -O2 -g -ggdb $< -o $@
+nearest: nearest.o
+ @echo Linking $<...
+ @$(CPP) -Wall -O2 -g -ggdb $< -o $@
+
.PHONY: beauty clean uninstall
clean:
new file mode 100644
--- /dev/null
+++ b/nearest.cc
@@ -0,0 +1,79 @@
+/**
+ * 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;
+}