栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ map的一道key排序面试题引发的思考

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ map的一道key排序面试题引发的思考

问题描述:map里面的key可以是自定义的数据类型?如果是,该自定义数据类型有什么特点?
答案:key可以是自定义数据类型,需要重载operator<运算符,因为map实现的机制是红黑树,默认是根据key的ASCII进行排序,如果是自定义数据类型,需要指定排序规则

c++ 实现demo
class A{
public:
    A(std::string name_): name(name_){}
    //运算符重载
    bool operator<(const A& a) const{
        return this->name > a.name ? true : false;
    }
    //重载输出运算符,否则first元素无法输出
    friend std::ostream& operator<<(std::ostream& output, const A& a);
private:
    std::string name;
};

std::ostream& operator<<(std::ostream& output, const A& a){
        output<
    std::map map_{{A("wang"), 28}, {A("lia"), 30}};
    for(auto& element : map_){
        std::cout< 

输出结果:[root@iZuf60vfno7b9n6pw24kdmZ admin]# ./main
wang 28
lia 30

通过自定义谓词进行排序

通过谓词进行规则设定,然后排序,效果也是一样的。

class B{
public:
    friend class Compare;
    B(std::string name_): name(name_){}
    friend std::ostream& operator<<(std::ostream& output, const B& a);
private:
    std::string name;
};
std::ostream& operator<<(std::ostream& output, const B& a){
        output<
public:
    bool operator()(const B& a1, const B& a2){
        return a1.name > a2.name ? true : false;
    }
};
void test_04(){
    std::map map_;
    map_.insert(std::make_pair(B("wang"), 28));
    map_.insert(std::make_pair(B("lia"), 30));
    for(auto& element : map_){
        std::cout< 

输出:[root@iZuf60vfno7b9n6pw24kdmZ admin]# ./main
wang 28
lia 30

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847824.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号