gpt4 book ai didi

c++ - 具有自定义排序的 C++ 映射中的唯一索引

转载 作者:太空狗 更新时间:2023-10-29 20:13:59 25 4
gpt4 key购买 nike

我有一个像这样的 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;
};

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

std::map <Foo, int> bla;

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

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

这很好用,排序也很好用。但我的问题是,如何才能仅通过 unique_id 找到项目? find 函数需要一个 Foo,这需要一个 priority,我在查询时没有。

我更想将优先级存储在值中(而不是作为键),但我不知道如何按值排序。 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 将为您提供迭代器,该迭代器将遍历按键排序的项目。要按值遍历已排序项目并仍然使用映射,唯一的方法是将整个集合重写为另一个映射,键和值颠倒。

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

关于c++ - 具有自定义排序的 C++ 映射中的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18556452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com