[C++]高效使用关联容器的一些建议

关联容器

本文介绍在关联容器中常见的一些的问题以及提升使用关联容器的建议。

1. 理解相等(equality)和等价(equivalence)的区别。

相等是以operator==为基础的。等价是以operator<为基础的。

例如find的定义是相等,他用operator==来判断,这是比较容易理解的。

而等价关系是以“在已排序的区间中对象值的相对顺序”为基础的。也就是说,如果两个值中任何一个(按照既定的排列顺序)都在另一个的前面,那么他们就是等价的。

    !(w1 < w2) && !(w2 < w1);
    !c.key_comp()(x, y) && !c.key.comp(y, x);

key_comp()返回一个函数,并以x, y作为参数传入。

具体而言,我们设想一个不区分string大小的set,来具体说明问题。

#include <iostream>
#include <set>
#include <string>
using namespace std;
bool ciCharLess(char c1, char c2) {
// 在C++中,char可能是有符号的也可能是无符号的,所以我们要转换为无符号的char,才能比较。
    return tolower(static_cast<unsigned char> (c1)) <
            tolower(static_cast<unsigned char> (c2));
}
bool ciStringCompare(const string& s1, const string& s2) {
    return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ciCharLess);
}
// It must be a struct but not be a class.
struct CIstring : public binary_function<string, string, bool> {
    bool operator() (const string& T1, const string& T2) const {
        return ciStringCompare(T1, T2);
    }
};
int main(int argc, char *argv[]) {
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值