sorted_list.h

来自「Implementation of genetic algorithm, to 」· C头文件 代码 · 共 120 行

H
120
字号
//---------------------------------------------------------------------------
#ifndef sorted_listH
#define sorted_listH

//---------------------------------------------------------------------------
#include <vector>
#include <boost/shared_ptr.hpp>

enum PORZADEK{ROSNACO, MALEJACO};
//---------------------------------------------------------------------------
template <typename T, bool sorted = false, PORZADEK = ROSNACO>
class TSortedList
{
  private:
	typedef std::vector<boost::shared_ptr<T> > list_type;
     typedef list_type::iterator iterator_type;

	boost::shared_ptr<list_type> list;
	iterator_type iter;

	T* temp;

	boost::shared_ptr<T> create(T* el)
	{
		boost::shared_ptr<T> p(el);
		return p;
	}

	void insert(T* el)
	{
		if(list->size())
		{
			iter = list->begin();
			for(unsigned i = 0; i < list->size(); i++, iter++)
			{
				if(*el < *(list->at(i).get()) && PORZADEK == ROSNACO)
				{
					list->insert(iter, create(el));
					return;
				}
				if(*el > *(list->at(i).get()) && PORZADEK == MALEJACO)
				{
					list->insert(iter, create(el));
					return;
				}
				if(i == list->size() - 1)
				{
					list->push_back(create(el));
					return;
				}
			}
		}
		else
			list->push_back(create(el));
	}

  public:
	TSortedList(void) : list(new list_type()) {}
	~TSortedList(void) {}

	unsigned add(T* el)
	{
		if(sorted) insert(el);
		else 	 list->push_back(create(el));

		return list->size() - 1;
	}

	T const* item(unsigned index) const
	{
		unsigned count = list->size();
		if(index < 0 || index >= count)
			return temp;

		return list->at(index).get();
	}

	T* item(unsigned index)
	{
		unsigned count = list->size();
		if(index < 0 || index >= count)
			return 0;

		return list->at(index).get();
	}

	bool erase(unsigned index)
	{
		unsigned count = list->size();
		if(index < 0 || index >= count)
			return false;

		iter = list->begin();
		list->erase(iter + index);
		return true;
	}

	unsigned count(void) const
	{
		return list->size();
	}

	void clear(void)
	{
		list->clear();
	}

	TSortedList& operator=(TSortedList& L)
	{
		L.clear();
		for(int i = 0; i < list->count; i++)
			L.add(list->item(i));
		return L;
     }
};
//---------------------------------------------------------------------------
#endif /* plik 'sorted_list.h' */


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?