stl的比较器:自定义数据排序方式,set忽略大小写

14 篇文章 0 订阅

stl自定义的比较器主要用于实现容器中元素的比较。比较器的定义的方式主要有下面三种:

1.普通函数

对vector数值进行降序排序
sort默认是升序的,这里通过cmp函数改成降序排序。如果将cmp的返回值改成a<b就还是升序。

bool cmp(int a, int b) {
    return a > b;
}

int main() {
    std::vector<int> data {1, 6, 3, 5, 9 ,20};
    std::sort(data.begin(), data.end(), cmp);
    for_each(data.begin(), data.end(), [](int i){std::cout << i << std::endl; });
    return 0;
}

对vector字符串进行反字典排序
sort默认是字典序的,这里通过cmp函数改成降序排序。如果将cmp的返回值改成a<b就还是字典序。

bool cmp(std::string a, std::string b) {
    return a > b;
}

int main() {
    std::vector<std::string> name_list{"zhoujielun", "linjunjie", "axin", "xiaojingteng"};
    std::sort(name_list.begin(), name_list.end(), cmp);
    for_each(name_list.begin(), name_list.end(), [](std::string i){std::cout << i << std::endl; });
    return 0;
}
2.定义全局的operator<

适用于一些自定义的类型,根据其中一个属性进行排序
例如将根据同学的分数,降序排列

struct Person{
    Person(std::string name, float score)
        :name_(name), score_(score) {}
	std::string name_;
	float score_;
};

bool operator<(const Person a, const Person b) {
    return a.score_ > b.score_;
}

int main() {
    std::vector<Person> data {{"zhangsan", 90}, {"lisilisi", 70}, {"wanger", 65}, {"xiaowu", 95}};
    std::sort(data.begin(), data.end());
    for_each(data.begin(), data.end(), [](Person i){std::cout << i.name_ << ":" << i.score_ << std::endl; });
    return 0;
}
3.仿函数

仿函数是可调用对象的一种,是指一个具有operator()成员函数的类对象
前面都是举例的排序,下面将set改为忽略大小写,即对字符串的大小写不敏感

struct Cmp {
    bool operator()(std::string const&a, std::string const& b) const {
        return strcasecmp(a.c_str(), b.c_str()) < 0;
    }
};

int main() {
    std::set<std::string, Cmp> name_list{"zhoujielun", "linjunjie", "axin", "xiaojingteng"};
    for_each(name_list.begin(), name_list.end(), [](std::string i){std::cout << i << std::endl; });

    name_list.insert("ZHoujieLun");
    name_list.insert("ZHOUJIELUN");
    name_list.insert("ZHoujieLUN");
    for_each(name_list.begin(), name_list.end(), [](std::string i){std::cout << i << std::endl; });
    return 0;
}

可以看到前后两次输出都是一样的。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值