STL Application 1

(1) class hierarchy

(2) polymorphism, pointer of base class

(3) function object

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

class Shape{
public:
    virtual void Draw() = 0;
    virtual char GetMark() = 0;
    virtual ~Shape(){}
};

class Circle : public Shape{
public:
    Circle(double r_, char mark_):r(r_),mark(mark_){}
    double GetR() {return r;}
    virtual char GetMark(){ return mark;}
    virtual void Draw(){ cout << "Draw a circle..." << endl;}
    void show(){ cout << "Circle with r" << r << endl; }
    bool operator < (Circle& c){ return r < c.GetR(); }
    virtual ~Circle(){}
private:
    double r;
    char mark;
};

class Square : public Shape{
public:
    Square(double width_, char mark_):width(width_),mark(mark_){}
    double GetWidth(){ return width;}
    virtual char GetMark(){ return mark;}
    virtual void Draw(){ cout << "Draw a square..." << endl; }
    void show(){ cout << "Square with width" << width << endl; }
    bool operator < (Square& s) { return width < s.GetWidth(); }
    virtual ~Square(){}

private:
    double width;
    char mark;
};

template<class T>
class ShapeCompare{
public:
    bool operator()(T* t1, T* t2){
        return *t1 < *t2;
    }
};

int main(){
    vector<Shape*> vecShape;
    Circle* c1 = new Circle(10.0, 'C');
    Circle* c2 = new Circle(7.0, 'C');
    Shape* s1 = new Square(10.0, 'S');
    Shape* s2 = new Square(5.0, 'S');

    vecShape.push_back(c1);
    vecShape.push_back(s1);
    vecShape.push_back(c2);
    vecShape.push_back(s2);

    vector<Circle*>vecCircle;
    vector<Square*>vecSquare;

    for(unsigned i=0; i<vecShape.size();i++){
        Shape* pShape = vecShape.at(i);
        char mark = pShape->GetMark();
        if(mark == 'C'){
            vecCircle.push_back((Circle*) pShape);
        } else {
            vecSquare.push_back((Square*) pShape);
        }
    }

    sort(vecSquare.begin(), vecSquare.end(), ShapeCompare<Square>());
    sort(vecCircle.begin(), vecCircle.end(), ShapeCompare<Circle>());

    for(unsigned i=0; i<vecSquare.size(); i++){
            Square* ps = vecSquare.at(i);
            ps->Draw();
    }

    for(unsigned i=0; i<vecCircle.size(); i++){
            Circle* ps = vecCircle.at(i);
            ps->Draw();
    }

    for(unsigned i=0; i<vecShape.size(); i++){
        Shape* pShape = vecShape.at(i);
        delete pShape;
        pShape = NULL;
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值