c++ hash_map用法总结

本文总结了C++ STL库中的hash_map使用方法,包括find()和insert()的使用,强调了头文件引用、键值对插入、查找返回值及获取value的注意事项。还提到了使用string作为key时可能出现的编译错误及其解决方法。
摘要由CSDN通过智能技术生成

c++ STL库里有自定义的hash_map 方法,但是使用起来并不是那么方便

hash_map主要的方法有

find(),insert()

我结合官方API说明一下他们的用法


一、需要特别注意的地方,

1.头文件的引用

2.如何插入一个<key,value>键值对(参考一下代码)

3.find()的返回值

4.如何获取某一个key值相应的value值

 hm1_RcIter -> second
分别用。first,和,second,指代key和value的值

// hash_map_find.cpp
// compile with: /EHsc
#define _DEFINE_DEPRECATED_HASH_CLASSES 0
#include <hash_map>
#include <iostream>

int main( )
{
   using namespace std;
   using namespace stdext;
   hash_map <int, int> hm1;
   hash_map <int, int> :: const_iterator hm1_AcIter, hm1_RcIter;
   typedef pair <int, int> Int_Pair;

   hm1.insert ( Int_Pair ( 1, 10 ) );
   hm1.insert ( Int_Pair ( 2, 20 ) );
   hm1.insert ( Int_Pair ( 3, 30 ) );

   hm1_RcIter = hm1.find( 2 );
   cout << "The element of hash_map hm1 with a key of 2 is: "
        << hm1_RcIter -> second << "." << endl;

   // If no match is found for the key, end( ) is returned
   hm1_RcIter = hm1.find( 4 );

   if ( hm1_RcIter == hm1.end( ) )
      cout << "The hash_map hm1 doesn't have an element "
           << "with a key of 4." << endl;
   else
      cout << "The element of hash_map hm1 with a key of 4 is: "
           << hm1_RcIter -> second << "." << endl;

   // The element at a specific location in the hash_map can be found 
   // using a dereferenced iterator addressing the 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值