開發C++時,選擇合適的數據結構是一個十分重要的步驟。因此,必須對每一個數據結構的原理及應用場景都有所了解。
boost::unordered_map和std::map都是一種關聯式容器,且原理類似,通過存儲key-value鍵值對,可通過key快速檢索到value,並且key是不重復的。但是,它們之間有一些區別,下面將逐一介紹。
排序區別:
map是有序的:按照operator<比較判斷元素的大小,並選擇合適的位置插入到樹中;
unordered_map是無序的:計算元素的Hash值,根據Hash值判斷元素是否相同。
用法區別:
對於key是自定義的類型, map的key需要定義operator<,內置類型(如,int)是自帶operator<;
對於key是自定義的類型,unordered_map需要定義hash_value函數並且重載operator==,內置類型都自帶該功能。
應用區別:
如果元素需要排序,則使用map;
如果需要高效率和低內存,則使用unordered_map。
————————————————
版權聲明:本文為CSDN博主「yz930618」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/yz930618/article/details/84783947
示例代碼一
#include <stdio.h>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
void main(){
unordered_map<string,int> months;
//插入數據
cout<<"insert data"<<endl;
months["january"]=31;
months["february"] = 28;
months["march"] = 31;
months["september"] = 30;
//直接使用key值訪問鍵值對,如果沒有訪問到,返回0
cout<<"september->"<<months["september"]<<endl;
cout<<"xx->"<<months["xx"]<<endl;
typedef unordered_map<int,int> mymap;
mymap mapping;
mymap::iterator it;
mapping[2]=110;
mapping[5]=220;
const int x=2;const int y=3;//const是一個C語言(ANSI C)的關鍵字,它限定一個變量不允許被改變,產生靜態作用,提高安全性。
//尋找是否存在鍵值對
//方法一:
cout<<"find data where key=2"<<endl;
if( mapping.find(x)!=mapping.end() ){//找到key值為2的鍵值對
cout<<"get data where key=2! and data="<<mapping[x]<<endl;
}
cout<<"find data where key=3"<<endl;
if( mapping.find(y)!=mapping.end() ){//找到key值為3的鍵值對
cout<<"get data where key=3!"<<endl;
}
//方法二:
it=mapping.find(x);
printf("find data where key=2 ? %d\n",(it==mapping.end()));
it=mapping.find(y);
printf("find data where key=3 ? %d\n",(it==mapping.end()));
//遍歷hash table
for( mymap::iterator iter=mapping.begin();iter!=mapping.end();iter++ ){
cout<<"key="<<iter->first<<" and value="<<iter->second<<endl;
}
system("pause");
}
示例代碼二
static boost::unordered_map<int32, IMessagePtr(*)()> * GetMessageTable()
{
static std::pair<int32, IMessagePtr(*)()> __DefineMessages[] = { std::pair<int32, IMessagePtr(*)()>(SerializeMessage::RESERVE_IDENTITY, SerializeMessage::Create) };
static boost::unordered_map<int32, IMessagePtr(*)()> __MessageTable(__DefineMessages, __DefineMessages + sizeof(__DefineMessages) / sizeof(__D efineMessages[0]));
return &__MessageTable;
}
bool MessageFactory::Register(int32 id, IMessagePtr(*creator)())
{
return core_insert_container(*GetMessageTable(), id, creator);
}
template<typename T, typename U, typename V>
inline bool insert_container(std::map<T, U, V> &container, const T &key, const U &value)
{
return container.insert(std::pair<T, U>(key, value)).second;
}