终于学到类的设计了
Problem 2: A simple class
设计一个简单的类
class Rectangle{
public:
Rectangle(int x, int y, double width, double height);//构造函数
~Rectangle(); //析构函数
double getPrimeter(); //获取周长
double getArea(); //获取面积
void translate(int dx, int dy); //
void scale(double factor); //缩放比例
void print();
private:
int x, y;
double width, height;
};
//设计Rectangle()函数,由于构造函数选择了与实例变量相同的变量名,所以要用this
Rectangle::Rectangle(int x, int y, double width, double height){
this->x = x;
this->y = y;
this->width = width;
this->height = height;
}
Problem 3: Function Pointers and Templates
a)模板函数
//编写模板函数
template <typename ValueType> //ValueType作占位符,代表任何类型
ValueType FindMax(Vector<ValueType> & v, int (cmpFn)(ValueType, ValueType) = OperatorCMp)
{
ValueType max = v[0]; //
for(int i = 0; i < v.size(); i++)
{
if (cmpFn(max, v[i]) < 0) //cmpFn是比较函数,负值表明后者更大
{
max = v[i];
}
}
return max;
}
b) 可能光看上面不知道比较函数有啥用,看了下面就知道,自己定义的数据类型需要自己设计比较函数。
struct Car{
string name;
int weight;
int numAirbags;
};
int CarCompare(Car first, Car second)
{
if(first.numAirbags == second.numAirbags)
return first.weight - second.weight;
else return first.numAirbags - second.numAirbags;
}
int main()
{
Vector<Car> cars;
Car safestCar = FindMax(cars, CarCmpare);
cout << safestCar.name <<endl;
return 0;
}
Problem 4: Templatized Functions
还是模板的例子,可以看出为使模板实现各种数据类型的功能,需要自己手动制作各种各样的判别函数,比较函数等
template <typename ElemType>
void Filter(Queue<ElemType> & q, bool (predFn)(ElemType))
{
int size = q.size()
for (int i=0 ; i< size ; i++ )
{
ElemType currValue = dequeue(); //currValue是判别函数,如要删除则为1
if(!predFN(currValue)) //取0时
{
q.enqueue(currVaue); //入队,不删除
}
}
}
Problem 5: More Templatized Functions
a)删除重复的东西, 可以看出这个算法很精妙,一个个拿后面的数和前面的比较进行删除,两个循环解决问题
template <typename ElemType>
void RemoveDuplicates(Vector<ElemType> & v, int (cmpFN)(ElemType, ElemType))
{
for(int i=0; i< v.size(); i++)
{
for(int k = v.size() -1; k > i ; k--)
{
if(comFn(v[i],v[k]) ==0 )
v.removeAt(k);
}
}
}
b) 加个简单的比较函数
template <typename ElemType>
int Compare(int first, int second)
{
if (first == second || first + second == 0)
return 0;
else return 1;
}
void RemoveDuplicates(Vector<ElemType> & v, int (cmpFN)(ElemType, ElemType))
{
for(int i=0; i< v.size(); i++)
{
for(int k = v.size() -1; k > i ; k--)
{
if(comFn(v[i],v[k]) ==0 )
v.removeAt(k);
}
}
}
int main()
{
Vector<int> vec;
RemoveDuplicates(vec, Compare);
return 0;
}