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

1.双向队列(deque)

void testDeque() 
{
    deque<int> data;
    data.push_back(1);
    data.push_front(2);
    data.push_back(3);
    cout << data.size() << endl;
    while (!data.empty()) 
    {
        cout << data.front() << "\t";
        data.pop_front();
    }
    cout << endl;
    deque<string> strQue;
    strQue.push_front("love");
    strQue.push_front("Andsen");
    strQue.push_back("Young");
    while (!strQue.empty()) 
    {
        cout << strQue.back() << "\t";
        strQue.pop_back();
    }
    cout << endl;
}
class MM 
{
public:
    MM(string name, int age) :name(name), age(age) {}
    friend ostream& operator<<(ostream& out, const MM& object);
protected:
    string name;
    int age;
};
ostream& operator<<(ostream& out, const MM& object) 
{
    out << object.name << "\t" << object.age << endl;
    return out;
}
void testUserData() 
{
    deque<MM> mmQue;
    mmQue.push_back(MM("小可爱", 18));
    mmQue.push_front(MM("小甜心", 20));
    cout << mmQue.size() << endl;
    while (!mmQue.empty())
    {
        cout << mmQue.front();
        mmQue.pop_front();
    }
}

2.简单实现deque

template <class _Ty>
class MyDeque
{
public:
    MyDeque() {}
    void push_back(_Ty data) { mem.push_back(data); }
    void push_front(_Ty data) { mem.push_front(data); }
    void pop_front() { mem.pop_front(); }
    void pop_back() { mem.pop_back(); }
    int size() { return mem.size(); }
    bool empty() { return mem.empty(); }
    _Ty front() { return mem.front(); }
    _Ty back() { return mem.back(); }
protected:
    list<_Ty> mem;
};

 

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