C++ unordered_map


是一種特殊的map,查詢鍵值的復雜度為O(1),但是map查詢鍵值的復雜度為O(log N)

有的編譯器使用時要加入下面的頭文件:

#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif

下面看幾個函數:

#include <bits/stdc++.h>
#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif
using namespace std;
const int maxn = 1e5 + 100;
unordered_map<int, int> fa;
int main() {
    fa[1]=2;
    fa[2]=3;
    fa[3]=4;
    fa[4]=0;
    //count函數 查詢鍵值是否有值  返回0或者1 
    cout<<fa.count(5)<<endl;//0
    cout<<fa.count(4)<<endl;//1
    cout<<fa.count(3)<<endl;//1
    if(fa.find(1)==fa.end()) cout<<"不存在"<<endl;//存在 
    else cout<<"存在"<<endl;
    if(fa.find(4)==fa.end()) cout<<"不存在"<<endl;//存在 
    else cout<<"存在"<<endl;  
    if(fa.find(5)==fa.end()) cout<<"不存在"<<endl;//不存在 
    else cout<<"存在"<<endl; 
    
    //遍歷fa
    unordered_map<int,int>::iterator it;
    for(it=fa.begin();it!=fa.end();)
    {
        cout<<it->first<<" "<<it->second<<endl;
        ++it;
     } 
     cout<<endl<<endl;
     //移除某個鍵值為奇數的元素 
     for(it=fa.begin();it!=fa.end();)
    {
        if(it->first%2==1) it=fa.erase(it); //刪除之后指向下一個 
        else ++it;
     } 
     for(it=fa.begin();it!=fa.end();)
    {
        cout<<it->first<<" "<<it->second<<endl;
        ++it;
     } 
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM