c++ (简单实现 list 与 find_if)

#include <iostream>
#include <utility>
using namespace std;

namespace mylist
{
	template<typename T>
	struct list_node
	{
		explicit list_node(const T& x):data(x), next(nullptr), prev(nullptr)
		{
			
		}
		list_node* prev;
		list_node* next;

		T data;
	};

	template<typename T>
	struct list_iterator
	{
		explicit list_iterator() {}
		explicit list_iterator(list_node<T>* n) :node(n) {};

		T& operator *()
		{
			return node->data;
		}

		list_iterator& operator++()//++i
		{
			node = node->next;
			return *this;
		}

		list_iterator operator++(int)//i++
		{
			list_node n(*this);
			node = node->next;
			return n;
		}

		bool operator!=(const list_iterator& obj)
		{
			return node != obj.node;
		}

		bool operator==(const list_iterator& obj)
		{
			return node == obj.node;
		}

		list_node<T>* node; //指向节点的指针
	};

	template<typename T>
	class clist
	{
	public:
		using iterator = list_iterator<T>;
		explicit clist()
		{
			void *point = new char[sizeof(list_node<T>)];
			head = reinterpret_cast<list_node<T>*>(point);
			head->next = head;
			head->prev = head;
		}

	public:
		iterator begin()
		{
			return iterator(head->next);
		}

		iterator end()
		{
			return iterator(head);
		}

		void push_back(const T& node)
		{
			list_node<T>* pNode = new list_node<T>(node);
			if (head->next == head)
			{
				pNode->next = head;
				pNode->prev = head;
				head->next = pNode;
				head->prev = pNode;
			}
			else
			{
				pNode->next = head;
				pNode->prev = head->prev;

				head->prev->next = pNode;
				head->prev = pNode;
			}
		}

		~clist()
		{
			clear();
			delete (void*)head;
			head = nullptr;
		}
	private:
		void clear()
		{
			if (head->next !=  head)
			{
				list_node<T>* currnode = head->next;
				while (currnode != head)
				{
					list_node<T>* nextnode = currnode->next;
					delete currnode;
					currnode = nextnode;
				}
			}
		}

		list_node<T>* head;
	};

}

#include <list>
template <typename T, typename U>
T w_find_if(T first, T last, U obj)
{
	for (; first != last; ++first)
	{
		if (obj(*first))
		{
			break;
		}
	}
	return first;
}
int main(int arg, char** args)
{
	mylist::clist<int> _list;
	_list.push_back(1);
	_list.push_back(3);
	_list.push_back(5);
	_list.push_back(9);
	_list.push_back(20);
	auto ret = w_find_if(_list.begin(), _list.end(), [](int value)->bool {
		if (value == 3)
			return true;
		return false;

		});
	if (ret != _list.end())
	{
		cout << "value === 3" << endl;
	}

	return 0;
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页