首页 > 代码库 > c++数据结构 --unorder_map

c++数据结构 --unorder_map

#include <iostream>
#include <unordered_map>
using namespace std;
class Book
{
private:
    string num;
    string name;
public:
    Book() {};
    Book(string num,string name) { this ->name = name;this ->num = num;};
    string getNum() { return num;};
    string getName() { return name;};
};
int main()
{
    unordered_map<string,Book>lib;
    Book b("001","高级语言程序设计") ;
    lib[b.getNum()] = b;
    unordered_map<string,Book>::iterator it;
    it  = lib.find( *(new string("001")) );
    if ( it != lib.end() )
        cout << (it ->second).getName();
    else
        cout << "没有给元素!";

    return 0;
}
技术分享
unsigned int JSHash(const char *str){
    unsigned int hash = 1315423911;
    while (*str){
        hash ^= ((hash << 5) + (*str++) + (hash >> 2));
    }
    return (hash & 0x7FFFFFFF);
}

class StrHash{
public:
    size_t operator()(const string& s) const {
        return JSHash(s.c_str());
    }
};

class StrCompare{
public:
    bool operator()(const string& a,const string& b) const {
        return (a==b);
    }
};
字符哈希及字符串比较函数

note:

1.内部实现为: hasht_table

2.示例中,已string为key,unorder_map已经为string创建了hash值计算函数,所以无需重写(貌似是这样的)

3.(Todo)详解具体使用方法

c++数据结构 --unorder_map