Shoping(map)

關於map:

map的特性是,所有元素都會根據元素的減值自動被排序。 map的所有元素都是pair,同時擁有實值(value)和鍵值(key)。
pair的第一個元素會被視爲鍵值,第二個元素會被視爲實值。 map不允許兩個元素擁有相同的鍵值。
key值不可修改!

map中插入元素:
注意後加入的在 begin一側,即後入的排在前面;
可利用rbegin 和 rend 反轉輸出,得到正確的順序

//第一種
map[key]=value;
//第二種
map<int,string> maplive;
pair<int,string> value(1,"a");
maplive.insert(value);

begin() 返回指向map頭部的迭代器
end() 返回指向map末尾的迭代器
clear() 刪除所有元素
count() 返回指定元素出現的次
empty() 如果map爲空則返回true
erase() 刪除一個元素
find() 查找一個元素
get_allocator() 返回map的配置器
insert() 插入元素
key_comp() 返回比較元素key的函數
lower_bound() 返回鍵值>=給定元素的第一個位置
max_size() 返回可以容納的最大元素個數
rbegin() 返回一個指向map尾部的逆向迭代器
rend() 返回一個指向map頭部的逆向迭代器

size() 返回map中元素的個數
swap() 交換兩個map
upper_bound() 返回鍵值>給定元素的第一個位置
value_comp() 返回比較元素value的函數

hash_map

hash_map是基於hash table(哈希表)。
哈希表最大的優點,就是把數據的存儲和查找消耗的時間大大降低,幾乎可以看成是常數時間;而代價僅僅是消耗比較多的內存。然而在當前可利用內存越來越多的情況下,用空間換時間的做法是值得的。另外,編碼比較容易也是它的特點之一。
基本原理:使用一個下標範圍比較大的數組來存儲元素。可以設計一個函數(哈希函數,也叫做散列函數),使得每個元素的關鍵字都與一個函數值(即數組下標,hash值)相對應,於是用這個數組單元來存儲這個元素;也可以簡單的理解爲,按照關鍵字爲每一個元素“分類”,然後將這個元素存儲在相應“類”所對應的地方,稱爲桶。
不能夠保證每個元素的關鍵字與函數值是一一對應的,因此極有可能出現對於不同的元素,卻計算出了相同的函數值,這樣就產生了“碰撞” —— 把不同的元素分在了相同的桶之中
hash_map,首先分配一大片內存,形成許多桶。是利用hash函數,對key進行映射到不同區域(桶)進行保存
插入過程
得到key
利用hash函數得到hash值
得到桶值(一般用hash值對桶的個數求餘)
存放key和value在桶內
取值過程:
得到key值
計算hash值
得到桶號
查找該桶內是否有和key值相同的,若無,則未找到(比較函數)
若有,返回找到的值

默認hash 和比較函數

#include<iostream>
using namespace std;
#include<hash_map>
#include<string>

hash_map<int,string> myHash;
myHash[100] = "100";
myHash[900] = "900";

hash_map::iterator iter =myHash.find(100);
if(iter != myHash.end())
.....
//未聲明hash函數和比較函數的,將使用默認的;
hash_map<int, string> myMap;
//等同於:
hash_map<int, string, hash<int>, equal_to<int> > myMap;

struct hash<int> {
        size_t operator()(int __x) const { return __x; }
};

key值只要是下列的類型,就可以不寫hash函數

struct hash<char*>
struct hash<const char*>
struct hash<char> 
struct hash<unsigned char> 
struct hash<signed char>
struct hash<short>
struct hash<unsigned short> 
struct hash<int> 
struct hash<unsigned int>
struct hash<long> 
struct hash<unsigned long>

若沒有則必須自定義hash函數,如string類

struct str_hash{
        size_t operator()(const string& str) const
        {
                unsigned long __h = 0;
                for (size_t i = 0 ; i < str.size() ; i ++)
                __h = 5*__h + str[i];
                return size_t(__h);
        }
};
//如果你希望利用系統定義的字符串hash函數,你可以這樣寫:
struct str_hash{
        size_t operator()(const string& str) const
        {
                return __stl_hash_string(str.c_str());
        }
};

在聲明自己的哈希函數時要注意以下幾點:

使用struct,然後重載operator().
返回是size_t
參數是你要hash的key的類型。
函數是const類型的。

hash_map 的比較函數

在map中的比較函數,需要提供less函數。
如果沒有提供,缺省的也是less< Key>
在hash_map中,要比較桶內的數據和key是否相等,因此需要的是是否等於的函數:equal_to< Key> 。
equal_to 源碼:

//本代碼可以從SGI STL
//先看看binary_function 函數聲明,其實只是定義一些類型而已。
template <class _Arg1, class _Arg2, class _Result>
struct binary_function {
        typedef _Arg1 first_argument_type;
        typedef _Arg2 second_argument_type;
        typedef _Result result_type;
};
//看看equal_to的定義:
template <class _Tp>
struct equal_to : public binary_function<_Tp,_Tp,bool>
{
        bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; }
};

若是自定義的類型,則需要自己構建compare函數:

使用equal_to< mystruct>作爲比較函數

struct mystruct{
	int myID;
	int value;
	bool operater== (const mystruct &my) const{
			return (myId == my.myID) && (value == my.value);
			}
	};

實現:

hash_map(mystruct,int,hash_str,equal_to<mystruct>) myHash;

構建函數對象

struct compare_str{
	bool operature()(const char* p1, const char* p2) const{
		 return strcmp(p1,p2)==0;
		 }
	};

實現:

hash_map(const char*,string,hash<char*>, compare_str);

hash_map(size_type n)

如果講究效率,這個參數是必須要設置的。
n 主要用來設置hash_map容器中hash桶的個數。桶個數越多,hash函數發生衝突的概率就越小,重新申請內存的概率就越小。
n越大,效率越高,但是內存消耗也越大。
const_iterator find(const key_type& k) const. 用查找,輸入爲鍵值,返回爲迭代器。

data_type& operator[](const key_type& k)

像使用數組一樣使用。
不過需要注意的是,當你使用[key]操作符時,如果容器中沒有key元素,這就相當於自動增加了一個key元素。因此當你只是想知道容器中是否有key元素時,你可以使用find。如果你希望插入該元素時,你可以直接使用[ ]操作符。
insert

在容器中不包含key值時,insert函數和[]操作符的功能差不多。但是當容器中元素越來越多,每個桶中的元素會增加,爲了保證效率,hash_map會自動申請更大的內存,以生成更多的桶。
因此在insert以後,以前的iterator有可能是不可用的
erase 函數。

在insert的過程中,當每個桶的元素太多時,hash_map可能會自動擴充容器的內存。
erase並不自動回收內存。因此你調用erase後,其他元素的iterator還是可用的。

map與hash_map

構造函數。hash_map需要hash函數,等於函數;map只需要比較函數(小於函數).
存儲結構。hash_map採用hash表存儲,map一般採用紅黑樹(RB Tree)實現。因此其memory數據結構是不一樣的。

總體來說,hash_map 查找速度會比map快,而且查找速度基本和數據數據量大小,屬於常數級別;而map的查找速度是log(n)級別。並不一定常數就比log(n)小,hash還有hash函數的耗時,明白了吧,如果你考慮效率,特別是在元素達到一定數量級時,考慮考慮hash_map。但若你對內存使用特別嚴格,希望程序儘可能少消耗內存,那麼一定要小心,hash_map可能會讓你陷入尷尬,特別是當你的hash_map對象特別多時,你就更無法控制了,而且hash_map的構造速度較慢。

#include <hash_map>
#include <string>
#include <iostream>

using namespace std;
//define the class
class ClassA{
        public:
        ClassA(int a):c_a(a){}
        int getvalue()const { return c_a;}
        void setvalue(int a){c_a;}
        private:
        int c_a;
};

//1 define the hash function
struct hash_A{
        size_t operator()(const class ClassA & A)const{
                //  return  hash<int>(classA.getvalue());
                return A.getvalue();
        }
};

//2 define the equal function
struct equal_A{
        bool operator()(const class ClassA & a1, const class ClassA & a2)const{
                return  a1.getvalue() == a2.getvalue();
        }
};

int main()
{
        hash_map<ClassA, string, hash_A, equal_A> hmap;
        ClassA a1(12);
        hmap[a1]="I am 12";
        ClassA a2(198877);
        hmap[a2]="I am 198877";
        
        cout<<hmap[a1]<<endl;
        cout<<hmap[a2]<<endl;
        return 0;
}
-bash-2.05b$ make my
c++  -O -pipe -march=pentiumpro  my.cpp  -o my
-bash-2.05b$ ./my
I am 12
I am 198877

題目:

Shopping
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6924 Accepted Submission(s): 2438

Problem Description
Every girl likes shopping,so does dandelion.Now she finds the shop is increasing the price every day because the Spring Festival is coming .She is fond of a shop which is called “memory”. Now she wants to know the rank of this shop’s price after the change of everyday.

Input
One line contians a number n ( n<=10000),stands for the number of shops.
Then n lines ,each line contains a string (the length is short than 31 and only contains lowercase letters and capital letters.)stands for the name of the shop.
Then a line contians a number m (1<=m<=50),stands for the days .
Then m parts , every parts contians n lines , each line contians a number s and a string p ,stands for this day ,the shop p 's price has increased s.

Output
Contains m lines ,In the ith line print a number of the shop “memory” ‘s rank after the ith day. We define the rank as :If there are t shops’ price is higher than the “memory” , than its rank is t+1.

Sample Input
3
memory
kfc
wind
2
49 memory
49 kfc
48 wind
80 kfc
85 wind
83 memory

Sample Output
1
2

我的代碼:

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int n, m, p;
    map< string, int> shop;
    while(cin>>n){
        string s;  //僅用於輸入商店名字
        for(int i=1; i<=n; i++)
            cin>>s;
        cin>>m;
        while(m--){
            for(int i=1; i<=n; i++){
                cin>>p>>s;
                shop[s] += p;
            }
            int rank = 1;  //排名
            map<string,int>::iterator it;
            for(it = shop.begin(); it != shop.end(); it++)
                if(it->second > shop["memory"])
                    rank++;
            cout<<rank<<endl;
        }
        shop.clear();
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章