使用STL map 用 string 做索引 插入删除数据

时间:2021-05-06 06:01:33

1、代码

 #include <map>
#include <string>
#include <stdio.h>
#include <vector>
#include <stdlib.h> using namespace std; class A
{
public:
int m_iX; public :
A();
A(int i);
~A();
}; A::A()
{
} A::A(int i)
{
m_iX = i;
} A::~A()
{
} typedef map<string, A *> MapA; void dumpMap(MapA & xMapA)
{
for(MapA::iterator pA = xMapA.begin(); pA != xMapA.end(); pA++)
{
printf("index : %s , value : %3d\n", pA->first.c_str(), pA->second->m_iX);
}
printf("-----------------------------------\n");
} int testOne()
{
printf("%s %d %s()\n", __FILE__, __LINE__, __func__); MapA xMapA; for(int i = ; i < ; i++)
{
A * a = new A(i);
char szIndex[] = {};
snprintf(szIndex, sizeof(szIndex), "%03d", i);
string strIndex = szIndex;
xMapA.insert(make_pair(strIndex, a));
}
dumpMap(xMapA);
printf("map size : %d\n", xMapA.size());
for(int i = ; i < ; i+=)
{
A * a = new A(i);
char szIndex[] = {};
snprintf(szIndex, sizeof(szIndex), "%03d", i);
string strIndex = szIndex;
MapA::iterator ppA = xMapA.find(strIndex);
if(ppA == xMapA.end())
{
printf("can not find : [%s]\n", strIndex.c_str());
continue;
}
xMapA.erase(ppA);
}
dumpMap(xMapA); printf("map size : %d\n", xMapA.size()); return ;
} int main(int argc, char * argv[])
{
testOne();
return ;
}

2、执行结果

./test-map
test-map.cpp testOne()
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
-----------------------------------
hash size :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
index : , value :
-----------------------------------
hash size :
over