C++第10课 STL容器 (三1)

时间:2021-09-07
本文章向大家介绍C++第10课 STL容器 (三1),主要包括C++第10课 STL容器 (三1)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.List

class MM {
public:
    MM(string name, int age) :name(name), age(age) {}
    string getName() const{ return name; }
    int getAge() const{ return age; }
protected:
    string name;
    int age;
};

//子函数描述排序准则
bool compareByName(const MM& obj1, const MM& obj2)
{
    return obj1.getName() < obj2.getName() ? true : false;
}

void testUserList()
{
    list<MM> mylist;

    MM temp[3] = { {"小可爱",13},{"小宝贝",16},{"小美女",18} };

    for (int i = 0; i < 3; i++)
    {
        mylist.push_back(temp[i]);
    }

    mylist.sort(compareByName);
}

2.简单模拟List

template<class _Ty>
struct Node {
    _Ty data;
    Node* next;
    Node(_Ty data) :data(data),next(nullptr) {}
};
template<class T>
class myList {
public:
    myList() {
        frontNode = nullptr;
        tailNode = nullptr;
        curSize = 0;
    }
    T front() {
        return frontNode->data;
    }
    T back() {
        return tailNode->data;
    }
    int size() {
        return curSize;
    }
    bool empty()
    {
        return curSize == 0;
    }
    void push_front(T data) {
        Node<T>* newNode = new Node<T>(data);
        newNode->next = frontNode;
        if (empty()) {
            tailNode = newNode;
        }
        frontNode = newNode;
        curSize++;
    }
    void push_back(T data) {
        Node<T>* newNode = new Node<T>(data);
        tailNode->next = newNode;
        if (empty()) {
            frontNode = newNode;
        }
        tailNode = newNode;
        curSize++;
    }
    class iterator {
    public:
        iterator() = default;
        iterator(Node<T>* node) :pmove(node) {}
        iterator operator++() {
            pmove = pmove->next;
            return *this;
        }
        iterator operator++(int) {
            this->pmove = this->pmove->next;
            return (*this);
        }
        bool operator!=(const iterator obj) const {
            return this->pmove != obj.pmove;
        }
        T operator*() const
        {
            return this->pmove->data;
        }
    protected:
        Node<T>* pmove;
    };
    iterator begin() {
        return (iterator(frontNode));
    }
    iterator end() {
        return (iterator(tailNode->next));
    }
protected:
    Node<T>* frontNode;
    Node<T>* tailNode;
    int curSize;
};

原文地址:https://www.cnblogs.com/creature-lurk/p/15240577.html