📄 hash_map.cpp
字号:
/*!
* \模块: hash_map.cpp
* \描述:
* STL Hasp Map的使用范例
* 参考资料:http://www.sgi.com/tech/stl/ http://www.sgi.com/tech/stl/hash_multimap.html
* 说明:使用BCB 6.0需要在Project->Option->Direc... include目录中加入:($BCB)\include\Stlport
*
* 版权:Copyright (c) 2004 biVod Studio.
* 版本:RCS: $Id: hash_map.cpp,v 1.2 2004/06/22 02:38:49 ylh Exp $
*
* 历史:
* 2004-6-21 创建(应理航)
*/
#include "hash_map"
#include <stdio.h>
using namespace std; // 这句一定要加
struct _eqStr {
bool operator() (const char *x, const char *y) const
{
return strcmp(x, y) == 0;
}
};
typedef struct
{
int key; // HASH的关键字
int item1;
float item2;
} SData;
typedef hash_multimap <const char*, SData *,
hash <const char*>, _eqStr> SDataHashMap;
int main(int argc, char* argv[])
{
SDataHashMap sDataHashMap;
for (int i = 0; i < 10; i++)
{
SData *sData = new SData[1]; // 这里必须是指针,并且new分配空间
sData->key = i;
sData->item1 = i * i;
sData->item2 = i * i * i;
// szKey必须是用new分配空间
char *szKey = new char[16];
sprintf(szKey, "%010d", sData->key);
sDataHashMap.insert(
SDataHashMap::value_type(szKey, sData));
sDataHashMap.insert(
SDataHashMap::value_type(szKey, sData));
}
printf("List of Hash Map (size: %d) \n", sDataHashMap.size());
for (SDataHashMap::iterator it = sDataHashMap.begin();
it != sDataHashMap.end(); it++)
{
printf("\t((%d: %d %f)\n", (*it).second->key, (*it).second->item1, (*it).second->item2);
}
printf("\nFind the item of key = 5\n");
char szTemp[16];
sprintf(szTemp, "%010d", 5);
SDataHashMap::iterator it = sDataHashMap.find(szTemp);
if (it != sDataHashMap.end())
{
printf("Item 5: (%d: %d %f) ", (*it).second->key, (*it).second->item1, (*it).second->item2);
printf("\nModify the item of key = 5\n");
(*it).second->item1 = 0;
(*it).second->item2 = 0;
printf("\nDelete the item of key = 5\n");
sDataHashMap.erase(it); // 会自动释放szKey分配的空间
// 也可以这样删除
// sDataHashMap.erase(szTemp);
}
else
{
printf("Can't find the item\n");
}
printf("List of Hash Map (size: %d) \n", sDataHashMap.size());
for (SDataHashMap::iterator it = sDataHashMap.begin();
it != sDataHashMap.end(); it++)
{
//sDataHashMap.erase(it);
printf("\t((%d: %d %f)\n", (*it).second->key, (*it).second->item1, (*it).second->item2);
}
// 清空Hasp Map,会自动释放所有内存
sDataHashMap.clear();
getchar();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -