// 8種關聯容器的用法.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
#include<map>
#include<set>
#include<string>
#include<unordered_set>
using namespace std;
class Info_Stu
{
public:
Info_Stu() = default;
Info_Stu(const string &a, const double b) :id(a), grades(b) {}
string get_id()const { return id; }
double get_grade()const { return grades; }
private:
string id;
double grades=0;
};
size_t hasher(const Info_Stu &fs)
{
return hash<string>()(fs.get_id());
}
bool eqop(const Info_Stu &lh, const Info_Stu &rh)
{
return lh.get_id() == rh.get_id();
}
bool compare(const Info_Stu &lh, const Info_Stu &rh)
{
return lh.get_id() < rh.get_id();
}
int main()
{
//關聯容器map和set,有序排列,關鍵不可重復!
//關聯容器multimap和multiset,有序排列,關鍵字可以重復(lower_bound,upper_bound迭代器,或者equal_range操作!)
//關聯容器unordered_map和unordered_set,無序排列,節省資源,關鍵字不可重復!
//關聯容器unordered_multimap和unordered_multiset,無序排列、關鍵字可重復!
//無序容器,當關鍵字本身就是無序時,使用無序容器節省資源!無序容器的性能取決于哈希函數的質量和桶的數量和大小!
//c.bucket_count() 正在使用桶的數目
//c.max_bucket_count() 容器能容納的最多的桶的數量
//c.bucket_size(n) 第n個桶中有多少元素
//c.bucket(k) 關鍵字為k的元素在哪個桶中
//local_iterator 可以用來訪問桶重元素的迭代器類型
//const_local_iterator const版本
//c.begin(n),c.end(n) 桶n的首元素迭代器
//c.cbegin(n),c.cend(n)
//c.load_factor() 每個桶的平均元素數量,返回float值
//c.max_load_factor() c中視圖維護平均桶的大小,返回float值
//c.rehash(n) 重組儲存,使得bucket_count>=n,且bucket_count>size/max_load_factor
//c.reserven() 重組儲存,使得c可以保存n個元素而不必rehash!
unordered_set<string> us;//對于自定義類,則需要自定義hash函數和==函數!
using fs_mulitset = unordered_multiset<Info_Stu, decltype(hasher)*, decltype(eqop)*>;
fs_mulitset stuinfo(42, hasher, eqop);//創建一個至少包含42個桶的空容器!
//X a(i, j, n, hf, eq)創建一個名為a的的空容器,它至少包含n個桶,將hf用作哈希函數,將eq用作鍵值相等謂詞,并插入區間[i, j]中的元素。如果省略了eq,將key_equal()用作鍵值相等謂詞;如果省略了hf,將hasher()用作哈希函數;如果省略了n,則包含桶數不確定
stuinfo.insert(Info_Stu("xiaohcng", 99));
stuinfo.insert(Info_Stu("xiaohang", 88));
stuinfo.insert(Info_Stu("xiaohbng", 88));
for (auto &r : stuinfo)
{
cout << r.get_id() << " : " << r.get_grade() << endl;
}
cout << "-------------"<<endl;
set<Info_Stu, decltype(compare)*> stuinfo2{ compare };
stuinfo2.insert(Info_Stu("xiaohcng", 99));
stuinfo2.insert(Info_Stu("xiaohang", 88));
stuinfo2.insert(Info_Stu("xiaohbng", 88));
for (auto &r : stuinfo2)
{
cout << r.get_id() << " : " << r.get_grade() << endl;
}
return 0;
}
8種關聯容器的用法
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
推薦閱讀更多精彩內容
- 每年到這個時候,身邊就會有很多人開始咳嗽、咳痰、流鼻涕、打噴嚏的,有些是感冒、有些是哮喘、有些是氣管炎,有些的鼻炎...
- 在使用ndk時,出現以下錯誤的解決方式 1、首先查看是否把項目配置是否正確,是否有下載以下開發包: 2、然后在pr...