gpt4 book ai didi

在 unordered_sets 上排序

转载 作者:行者123 更新时间:2023-12-02 01:53:11 25 4
gpt4 key购买 nike

我有一个每帧创建的项目列表,需要对其进行排序。每个 Item 的第一个排序依据的成员变量是 unordered_set

我已将其移动到系统中各处的有序集合中,以便我可以在项目列表中对其进行排序。但是我在另一个代码中遇到了性能问题。

请记住,每个项目都将在每帧的基础上被销毁和重新创建,我能做些什么来将它们保存在 unordered_set 中并对其进行排序吗?

class item
{
public:
unordered_set< int > _sortUS;
int _sortI;
//Other members to sort
bool operator<( const item& that ) const
{
if( _sortI != that._sortI )
{
return _sortI < that._sortI;
}
else if( _sortUS != that._sortUS )
{
return ??? // this is what I need. I don't know how to compare these without converting them to sets
}
}
};

最佳答案

给定std::unordered_set<Key, Hash>对于任意可哈希 Key , 你可以定义

template<class Key, class Hash = std::hash<Key>>
bool operator< (std::unordered_set<Key, Hash> const& L, std::unordered_set<Key, Hash> const& R)
{
return std::lexicographical_compare(
begin(L), end(L), begin(R), end(R),
[](Key const& kL, Key const& kR) {
return Hash()(kL) < Hash()(kR);
});
}

这将使用 Key 的散列索引的排序.然后,您可以在 item 上定义排序

bool operator< (item const& L, item const& R)
{
return std::tie(L.sortI, L.sortUS) < std::tie(R.sortI, R.sortUS);
}

std::tie将制作一个 std::tuple出于对您 item 成员的引用这样你就可以使用 operator<来自 std::tuple .

注意:您可以轻松证明上述比较是一个 StrictWeakOrder(std::sort 的要求),因为 std::tuple 都是比较和 lexicographical_compare有这个属性。

但是,unordered_set 的排序在其他方面是非常不寻常的。

  • 散列键索引与您迭代元素的顺序不对应(有一些模运算将散列键映射到容器中的索引)
  • unordered_set 添加元素可能导致先前排序的重新散列和无效

关于在 unordered_sets 上排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681803/

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