标签:
template<class NumericalType>
class DataCollection {
public:
NumericalType min() const;
NumericalType max() const;
NumericalType avg() const;
...
};
int findCubicleNumber(const string& employeeName)
{
// 定义静态map,存储 (employee name, cubicle number)
// pairs. 这个 map 是local cache。
typedef map<string, int> CubicleMap;
static CubicleMap cubes;
// try to find an entry for employeeName in the cache;
// the STL iterator "it" will then point to the found
// entry, if there is one (see Item 35 for details)
CubicleMap::iterator it = cubes.find(employeeName);
// "it"'s value will be cubes.end() if no entry was
// found (this is standard STL behavior). If this is
// the case, consult the database for the cubicle
// number, then add it to the cache
if (it == cubes.end()) {
int cubicle =
the result of looking up employeeName's cubicle
number in the database;
cubes[employeeName] = cubicle; // add the pair
// (employeeName, cubicle)
// to the cache
return cubicle;
}
else {
// "it" points to the correct cache entry, which is a
// (employee name, cubicle number) pair. We want only
// the second component of this pair, and the member
// "second" will give it to us
return (*it).second;
}
}
template<class T> // dynamic数组
class DynArray { ... }; // 模板
DynArray<double> a; // 在这时, 只有 a[0]
// 是合法的数组元素
a[22] = 3.5; // a 自动扩展
//: 现在索引0-22
// 是合法的
a[32] = 0; // 有自行扩展;
// 现在 a[0]-a[32]是合法的
template<class T>
T& DynArray<T>::operator[](int index)
{
if (index < 0) {
throw an exception; // 负数索引仍不合法
}
if (index >当前最大的索引值) {
调用new分配足够的额外内存,以使得
索引合法;
}
返回index位置上的数组元素;
}
DynArray::operator[]:
template<class T>
T& DynArray<T>::operator[](int index)
{
if (index < 0) throw an exception;
if (index > 当前最大的索引值) {
int diff = index – 当前最大的索引值;
调用new分配足够的额外内存,使得index+diff合法;
}
返回index位置上的数组元素;
}
DynArray<double> a; // 仅仅a[0]是合法的
a[22] = 3.5; // 调用new扩展
// a的存储空间到索引44
// a的逻辑尺寸
// 变为23
a[32] = 0; // a的逻辑尺寸
// 被改变,允许使用a[32],
// 但是没有调用new
More Effective C++----(18)分期摊还期望的计算
标签:
原文地址:http://blog.csdn.net/qianqin_2014/article/details/51332879