8种关联容器的用法

// 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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容