加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

带有自定义排序的C地图中的唯一索引

发布时间:2020-12-16 09:47:12 所属栏目:百科 来源:网络整理
导读:我有一个std :: map的自定义键,如下所示: struct Foo{ Foo(int _uid,int _priority) : unique_id(_uid),priority(_priority) {} bool operator(const Foo other) const { return priority other.priority; } int unique_id; int priority;}; 我正在使用以下
我有一个std :: map的自定义键,如下所示:

struct Foo
{
    Foo(int _uid,int _priority) : unique_id(_uid),priority(_priority) {}

    bool operator<(const Foo& other) const {    
        return priority < other.priority;       
    }

    int unique_id;
    int priority;
};

我正在使用以下代码创建地图:

std::map <Foo,int> bla;

这就是我插入项目的方式:

bla.insert(std::pair<Foo,int> (Foo(1,2),3) )

这很好用,排序也可以.但我的问题是,如何才能通过unique_id找到一个项目? find函数需要一个Foo,这需要一个优先级,当我查询它时我没有.

我更想将优先级存储在值中(而不是键),但我不知道如何按值排序. std :: map是正确的类/模板吗?

编辑:我没有使用boost的能力,优先级也不是唯一的.

解决方法

how can I find an item only by the unique_id?

这个问题的问题是该列表包含Foo类并按优先级排序.这使得通过unique_id搜索项目成为问题.

我建议的是创建一个新的std :: map

std::map <int,foo> uniqueId_To_FooClass;

当添加到bla新项目时,将其添加到uniqueId_To_FooClass.这样你就可以通过unique_id找到一个foo类

I would more like to store the priority in the value (not as the key),but I don’t know how I can sort by value then. Is a std::map the right class/template for that?

据我所知,std :: map将为您提供迭代器,它将遍历按键排序的项目.只能通过值来浏览已排序的项目,并仍然使用地图,是将整个集合重写为另一个地图,键和值相反.

你也可以看看Oli Charlesworth的here回答

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读