1. 程式人生 > >C++ 中map和list組合使用

C++ 中map和list組合使用

一、功能需求

1)既能根據鍵值快速查詢元素,同時又能根據元素插入順序pop出來該元素,該怎麼實現該容器?

二、程式碼實現

把map和list容器組合使用,封裝成一個全新的容器,以實現上述功能。程式碼如下:

//MapListUnion.h;
#include <map>
#include <list>
using namespace std;

//TKey 組合容器的鍵值;
//TValue 組合容器鍵值對應點的儲存資料;

template<typename TKey,typename TValue>
class CMapListUnion
{
public:
	struct CStornUnion
	{
		TKey keyindex;
		TValue value;
	};
	bool push(TKey Key, TValue temp)
	{
		auto itrM = m_map.find(Key);
		if (itrM != m_map.end())
		{
			return false;
		}

		CStornUnion stornUnion;
		stornUnion.keyindex = Key;
		stornUnion.value = temp;

		list <CStornUnion>::iterator itr;
		m_list.push_back(stornUnion);
		
		itr = m_list.end();
		itr--;
		m_map.insert(make_pair(Key, itr));

		return true;
	}
	void erase(TKey Key)
	{
		auto itr = m_map.find(Key);
		if (itr != m_map.end())
		{
			m_list.erase(itr->second);
			m_map.erase(itr);
		}
	}
	bool find(TKey Key, TValue &data)
	{
		auto itr = m_map.find(Key);
		if (itr != m_map.end())
		{
			CStornUnion &Union = *itr->second;
			data=Union.value;
			return true;
		}
		else
			return false;
	}
	bool pop(TValue &data)
	{		
		if (!m_list.empty())
		{
			CStornUnion &Union = m_list.front();
			data = Union.value;

			auto itr = m_map.find(Union.keyindex);
			if (itr != m_map.end())
			{
				m_map.erase(itr);
			}

			m_list.pop_front();

			return true;
		}
		else
		{
			return false;
		}
	}
public:
	 map<TKey, typename list <CStornUnion>::iterator>m_map;
	 list<CStornUnion>m_list;	 	
};

三、測試用例

#include "MapListUnion.h"
struct INFO
{
	int m_a;
	int m_b;
};

void testFunc()
{

	CMapListUnion<int, INFO*> gMapList;

	bool insertF = false;

	INFO* info1 = new INFO();
	info1->m_a = 221;
	info1->m_b = 222;
	insertF = gMapList.push(12, info1);

	INFO* info2 = new INFO();
	info2->m_a = 223;
	info2->m_b = 224;
	insertF = gMapList.push(11, info2);

	INFO* info3 = new INFO();
	info3->m_a = 225;
	info3->m_b = 226;
	insertF = gMapList.push(8, info3);

	INFO* info4 = new INFO();
	info4->m_a = 227;
	info4->m_b = 228;
	insertF = gMapList.push(24, info4);

	INFO* info5 = new INFO();
	info5->m_a = 229;
	info5->m_b = 220;
	insertF = gMapList.push(1, info5);

	INFO* info6 = new INFO();
	info6->m_a = 230;
	info6->m_b = 231;
	insertF = gMapList.push(1, info6);

	gMapList.erase(1);
	info1->m_a = 240;
	info1->m_b = 241;

	INFO* info7 = new INFO();
	info7->m_a = 232;
	info7->m_b = 233;
	insertF = gMapList.push(1, info7);

	INFO *ty = NULL;
	bool fg = gMapList.find(8, ty);
	bool fg3 = gMapList.find(13, ty);

	gMapList.pop(ty);
}

int main()
{	
	testFunc();
    return 0;
}

四、學習總結

1)該組合容器利用了Map的鍵值快速查詢功能;

2)該組合容器利用了List的儲存資料的順序性,同時也應用了刪除其某節點而不影響其他節點元素的地址的特性;