88
|
1 |
/**
|
|
2 |
* I am experimenting with templates...
|
|
3 |
*
|
|
4 |
*/
|
|
5 |
|
|
6 |
#include <iostream>
|
|
7 |
#include <list>
|
|
8 |
#include <vector>
|
|
9 |
#include <algorithm>
|
|
10 |
#include <stdexcept>
|
|
11 |
#include <iomanip>
|
|
12 |
|
|
13 |
using namespace std;
|
|
14 |
|
|
15 |
typedef short MYTYPE;
|
|
16 |
|
|
17 |
namespace cute {
|
|
18 |
template <typename Iter, typename T>
|
|
19 |
Iter find (Iter begin, Iter end, const T& query)
|
|
20 |
{
|
|
21 |
Iter it;
|
|
22 |
|
|
23 |
for (it = begin; it != end; it++) {
|
|
24 |
if (*it == query)
|
|
25 |
return it;
|
|
26 |
}
|
|
27 |
return it;
|
|
28 |
}
|
|
29 |
|
|
30 |
template <typename Iter, typename T>
|
|
31 |
void nearest (Iter begin, Iter end, const T& query)
|
|
32 |
{
|
|
33 |
Iter it, current;
|
|
34 |
|
|
35 |
current = it = cute::find (begin, end, query);
|
|
36 |
if (current == end)
|
|
37 |
return;
|
|
38 |
|
|
39 |
while (current != end) {
|
|
40 |
cout << *current << endl;
|
|
41 |
current++;
|
|
42 |
}
|
|
43 |
|
|
44 |
current = --it;
|
|
45 |
|
|
46 |
do {
|
|
47 |
cout << *current << endl;
|
|
48 |
} while ((current--) != begin);
|
|
49 |
}
|
|
50 |
}
|
|
51 |
|
|
52 |
int main (int argc, char **argv)
|
|
53 |
{
|
|
54 |
MYTYPE value, query;
|
|
55 |
vector <MYTYPE> vec;
|
|
56 |
list <MYTYPE> lis;
|
|
57 |
|
|
58 |
for (int i = 0; i < 10; i++) {
|
|
59 |
cout << "[" << std::setw (2) << i << "] Enter a value: ";
|
|
60 |
cin >> value;
|
|
61 |
if (!cin)
|
|
62 |
throw std::runtime_error ("BAD_INPUT");
|
|
63 |
else {
|
|
64 |
vec.push_back (value);
|
|
65 |
lis.push_back (value);
|
|
66 |
}
|
|
67 |
}
|
|
68 |
|
|
69 |
sort (vec.begin (), vec.end ());
|
|
70 |
lis.sort ();
|
|
71 |
|
|
72 |
cout << "Enter a value to search: ";
|
|
73 |
cin >> query;
|
|
74 |
|
|
75 |
cute::nearest (vec.begin (), vec.end (), query);
|
|
76 |
cute::nearest (lis.begin (), lis.end (), query);
|
|
77 |
|
|
78 |
return 0;
|
|
79 |
}
|