一、功能需求
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的存储数据的顺序性,同时也应用了删除其某节点而不影响其他节点元素的地址的特性;