C++关联容器

//初始化列表 初始化器必须能转为容器中元素的类型
   map<int, string> mp = {{1,"a"}, {2,"b"}};
   set<string> st = {"a", "d", "f"};

//map插入数据
    mp.emplace(4,"d");
    mp.insert(pair<int, string>(5,"e"));
    mp.insert(map<int, string>::value_type(7,"h"));
    mp.insert({3,"c"});
    mp.insert(make_pair(6, "f"));

 

//自定义一个Student类

class Student{

public:
    Student(string name) : name_(name){

    }

    bool operator < (const Student& rhs) const{
        return name_.length() < rhs.name_.length();
    }

    bool operator == (const Student& rhs) const {
        return name_ == rhs.name_;
    }
public:
    string name_;
};

 

对于有序容器map、multimap、set、multiset,关键字必须定义元素比较的方法。默认情况下,标准库使用关键字类型的<运算符来比较两个关键字。我们也可以提供自定义的操作来代替关键字的<运算符。

class Comp{

public:
    Comp(){}

    bool operator()(const Student& lhs, const Student& rhs){
        return lhs.name_.length() < rhs.name_.length();
    }
};

bool mycomp(const Student& lhs, const Student& rhs){
    return lhs.name_.length() < rhs.name_.length();
}

//map 自定义key
    Student s1("xm");
    Student s2("ysmgz");
    Student s3("wyh");

//使用重载的operator<
    map<Student, int> smp = {{s1, 10}, {s2, 20}, {s3, 15}};
//不需要将函数对象传入构造器,map会追踪类的定义,当需要比较时,动态构造对象并传递数据。
    map<Student, int, Comp> smp2 = {{s1, 10}, {s2, 20}, {s3, 15}};
//需要将函数传入构造器。实参使用mycomp和mycomp*是等价的。
    map<Student, int, decltype(mycomp)*> smp3(mycomp);

//默认情况下,无序容器使用关键字类型的==运算符来比较元素
//我们可以直接定义关键字是内置类型、string、智能指针类型的无序容器。
//自定义类型需要额外的定义函数。

size_t hasher(const Student& sd){
    return hash<string>()(sd.name_);
}

bool eqOp(const Student& lhs, const Student& rhs){
    return lhs.name_ == rhs.name_;
}
    using SD_multiset = unordered_set<Student, decltype(hasher)*, decltype(eqOp)*>;
//参数是桶大小、哈希函数指针、相等性判断指针。
    SD_multiset sd_store(10, hasher, eqOp);
//如果类定义了==运算符,那么可以只重载哈希函数
    unordered_set<Student, decltype(hasher)*> sd_store2(20, hasher);
    cout << sd_store.bucket_count() << std::endl;
    cout << sd_store2.bucket_count() << std::endl;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值