C++第10课 STL容器 (七)

1.优先队列((priority_queue)

void testCreatePriority_queue() {
    //最完整创建方式
    //1.存储的数据类型        int
    //2.底层实现的容器类型    vector<int>
    //3.排序准则  less<int>  greater<int>
    priority_queue<int, vector<int>, less<int>> data;    //从大到小
    //缺省写法
    priority_queue<int, vector<int>>  data2;            //默认就是从大到小
    priority_queue<int>  data3;                            //从大到小
    for (int i = 0; i < 10; i++) {
        data3.push(rand() % 100);
    }
    while (!data3.empty())
    {
        cout << data3.top() << "\t";
        data3.pop();
    }
    cout << endl;
}
class MM {
    friend ostream& operator<<(ostream& out, const MM& obj);
public:
    MM(string name, int age) :name(name), age(age) {}
    string getName() const { return name; }
    //注意函数属性必须为const
    bool operator>(const MM& obj) const;
protected:
    string name;
    int age;
};
ostream& operator<<(ostream& out, const MM& obj)
{
    out << obj.name << "\t" << obj.age << endl;
    return out;
}
bool MM::operator>(const MM& obj) const
{
    return this->age > obj.age ? true : false;
}

//通过类 去重载() 实现
//仿函数
class Compare
{
public:
    bool operator()(const MM& object1, const MM& object2) const
    {
        return object1.getName() > object2.getName();
    }
};

void testUserData() 
{
    priority_queue<MM,vector<MM>,greater<MM>> data;
    MM mm[3] = { {"小可爱",14},{"小宝贝",21},{"小帅哥",16} };
    for (int i = 0; i < 3; i++) {
        data.push(mm[i]);
    }
    while (!data.empty())
    {
        cout << data.top() << "\t";
        data.pop();
    }
    cout << endl;

    priority_queue<MM, vector<MM>, Compare> data2;
    MM mm2[3] = { {"小可爱",14},{"小宝贝",21},{"小帅哥",16} };
    for (int i = 0; i < 3; i++) {
        data2.push(mm2[i]);
    }
    while (!data2.empty())
    {
        cout << data2.top() << "\t";
        data2.pop();
    }
    cout << endl;

    //{} 说明作用,告诉编译器,Compare 是一个类型
    cout<<boolalpha << Compare{}(MM("1", 18), MM("2", 20)) << endl;

    Compare object;
    cout << boolalpha << object(MM("1", 18), MM("2", 20)) << endl;
    //重载的显式调用
    cout << boolalpha << object.operator()(MM("1", 18), MM("2", 20)) << endl;
}

2.简单实现priority_queue

template <class _Ty, class _Container = vector<_Ty>, class _Pr = less<_Ty>>
class My_Priority_queue
{
public:
    My_Priority_queue() {}
    void push(_Ty data) 
    {
        mem.push_back(data);
        sort(mem.begin(), mem.end(), _Pr());  
    }
    void pop() 
    {
        mem.erase(mem.begin());
    }
    const _Ty& top() 
    {
        return mem.front();
    }
    bool empty() const 
    {
        return mem.empty();
    }
protected:
    _Container mem;
};

 

posted @ 2021-09-08 21:20  Creature_lurk  阅读(31)  评论(0编辑  收藏  举报