C++第10课 STL容器 (三1)
Posted Creature_lurk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; };
以上是关于C++第10课 STL容器 (三1)的主要内容,如果未能解决你的问题,请参考以下文章