1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
#include <string>
using namespace std;
#define USE_CONST
template <typename C, typename T> int find (C, T , int); // now with int return type
#ifdef USE_CONST
template<typename T>
int find(const T list[], T key, int arraySize)
#else
template<typename T>
int find(T list[], T key, int arraySize) // no const
#endif
{
int low = 0;
int high = arraySize - 1;
while (high >= low)
{
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -1;
}
int main()
{
#ifdef USE_CONST
// now all const
const int intList[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
const double doubleList[] = {2.1, 4.2, 7.3, 10.4, 11.5, 45.6, 50.7,
59.8, 60.9, 66.10, 69.11, 70.12, 79.13};
const string stringList[] = {"abc","efg","xyz"};
#else
int intList[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
double doubleList[] = {2.1, 4.2, 7.3, 10.4, 11.5, 45.6, 50.7,
59.8, 60.9, 66.10, 69.11, 70.12, 79.13};
string stringList[] = {"abc","efg","xyz"};
#endif
cout << find(intList, 2, 13) << endl;
cout << find(doubleList, 59.8, 13) << endl;
cout << find(stringList, string("efg"), 5) << endl; // with string constructor
system("PAUSE"); // system() it evil!!
return 0;
}
|