# HG changeset patch # User Markus Bröker # Date 1241127528 -7200 # Node ID 91fbc3ea240b99e743282e3bbe76bed555ba4f6f # Parent b2f1756c17ca90a2dd271568695f8e2148bfa6c3 how to use templates We read 10 numbers from stdin and print the nearest values of a query. committer: Markus Bröker diff --git a/Makefile b/Makefile --- 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: diff --git a/nearest.cc b/nearest.cc new file mode 100644 --- /dev/null +++ b/nearest.cc @@ -0,0 +1,79 @@ +/** + * I am experimenting with templates... + * + */ + +#include +#include +#include +#include +#include +#include + +using namespace std; + +typedef short MYTYPE; + +namespace cute { + template + 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 + 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 vec; + list 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; +}