Essential C++ 3.1 节的代码练习——哨兵方式
#include "IncrementArray.hpp"
template <typename element>
element *find_address(element *array, int size, element &value)
{
if (! array || size < 1)
{
return 0;
}
for (int i = 0; i < size; ++i, ++array)
{
if ((*array) == value)
{
return array;
}
}
return 0;
}
template <typename element>
element *use_sentinel(element *first_address, element *sentinel, element &value)
{
if (! first_address || ! sentinel)
{
return 0;
}
for (; first_address != sentinel; ++first_address)
{
if ((*first_address) == value)
{
return first_address;
}
}
return 0;
}
int main()
{
cout << "Hello, Hal.\n";
string string_array[9] = {"hey", "hey", "you", "you", "I", "Don't", "Like", "Your", "Girlfriend"};
vector<string> avril(string_array, string_array + 9);
string who = "Girlfriend";
cout << "I don't like your Girlfriend. I know her address: " << find_address(&(avril[0]), 9, who) << endl;
int integer_array[4] = {1, 2, 3, 4};
int four = 4;
cout << "Where's 4? Oh, here it is: " << use_sentinel(&(integer_array[0]), &(integer_array[0]) + 5, four) << endl;
int ia[8] = { 1, 1, 2, 3, 5, 8, 13, 21};
double da[8] = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
string sa[4] = {"lim","aaa","ddd","dcc"};
int *pi = use_sentinel(ia,ia+8,ia[3]);
double *pd = use_sentinel(da,da+8,da[3]);
string *ps = use_sentinel(sa, sa+4, sa[2]);
cout << "ps=" << ps << " pd=" << pd << " pi=" << pi << endl;
return 0;
}
输出:
Hello, Hal.
I don't like your Girlfriend. I know her address: 0x1b1b70
Where's 4? Oh, here it is: 0x72fc6c
ps=0x72fbb0 pd=0x72fc08 pi=0x72fc3c
添加另一个函数:
template <typename elemType>
const elemType * find_ver5(const elemType *first,
const elemType *last, const elemType &value )
{
if ( ! first || ! last )
return 0;
// while first does not equal last,
// compare value with element addressed by first
// if the two are equal, return first
// otherwise, increment first to address next element
for ( ; first != last; ++first )
if ( *first == value )
return first;
return 0;
}
main函数中需要这么定义,加const。
const int *pi = find_ver5(ia,ia+8,ia[3]);
否则无法编译通过。