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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值