1. 程式人生 > >c++ map key為結構體

c++ map key為結構體

專案中需要將結構體作為hash的key,一開始用hash_map,但是結構體中多值比較一直失敗,所以嘗試了map。

hash_map 查詢速度會比map快,而且查詢速度基本和資料量大小無關,屬於常數級別;map的查詢速度是log(n)級別。hash還有hash函式的耗時。當有100w條記錄的時候,map也只需要20次的比較,200w也只需要21次的比較!所以並不一定常數就比log(n) 小。

hash_map對空間的要求要比map高很多,所以是以空間換時間的方法,而且,hash_map如果hash函式和hash因子選擇不好的話,也許不會達到你要的效果,


#include <string>
#include <cstring>
#include <iostream>
#include <map>
using namespace std;


typedef struct ip_tuple
{
    int src_port;
    int dst_port;
    char* src_ip;

    bool operator <(const ip_tuple& other) const
    {
        if (src_port < other.src_port)        //src_port按升序排序
        {
            return true;
        }
        else if (src_port == other.src_port)  //src_port相同,按dst_port升序排序
        {
            if(dst_port < other.dst_port)
            {
                return true;
            }
            else if(dst_port == other.dst_port)//dst_port,src_port相同,比較src_ip
            {
                if(strcmp(src_ip,other.src_ip)!=0)
                {
                    return true;
                }
            }

        }
        return false;
    }
} IPTUPLE;

int main()
{
    map<IPTUPLE, int>m_roadMap;
    for(int i=1; i<6; i++)
    {
        IPTUPLE it;
        it.src_port = i;
        it.dst_port = i*10;
        if(i==1)
        it.src_ip="aaa";
        if(i==2)
        it.src_ip="bbb";
        if(i==3)
        it.src_ip="ccc";
        if(i==4)
        it.src_ip="ddd";
        if(i==5)
        it.src_ip="bbb";
        m_roadMap.insert(make_pair(it, i*200));
    }
//==========
    IPTUPLE ite;
    ite.src_port = 2;
    ite.dst_port = 20;
    ite.src_ip="bbb";
    map<IPTUPLE, int>::iterator itor;

    itor = m_roadMap.find(ite);

    if (itor != m_roadMap.end())
    {
        cout<<itor->second;
    }

}