我有这样一个类:
struct Thing
{
unsigned index;
// more data members
};
我正在使用 std::map<Thing>
包含我的 Thing
秒。调用代码看起来像这样:
Thing myThing(/*...*/);
std::map<Thing> things;
things[myThing.index] = myThing;
// ...
Thing &thing3 = things[3];
我想知道是否有一种方法可以使用 Thing::index
直接无需隐式复制到 pair::first
.
我想我需要提供某种 Thing
比较运算符,但没关系。 std::set
可能有用,但我需要一个完整的 Thing
对象作为键:
std::set<Thing> things;
Thing &thing3 = *things.find(Thing(3));
重构除外Thing
进入std::pair
, 我可以用 STL 做得更好吗?
最佳答案
我不明白为什么
inline bool operator<(const Thing& a,const Thing& b) {
return (a.index<b.index);
}
std::set<Thing> things; // Uses comparison operator above
Thing &thing3 = *things.find(Thing(3));
并没有完全按照您的意愿行事。没有索引字段的重复/复制,并且键比较与 map 方法一样高效;有什么不喜欢的?
根据以下评论更新:
如果 Thing 太重量级以至于您不想复制它,那么您最终可能会得到更像这样的代码:
inline bool operator<(const shared_ptr<Thing>& a,const shared_ptr<Thing>& b) {
return (a->index < b->index);
}
std::set<shared_ptr<Thing>> things; // Uses comparison operator above
shared_ptr<Thing> key3(new Thing(3));
Thing &thing3 = *things.find(key3);
虽然恕我直言,覆盖指针值比较是相当邪恶的,但最好采用更详细的方式,即对设置模板参数进行显式“比较”参数。
要记住一件事(根据我自己对重量级对象的大优先级队列的经验):std::pair<trivial_key,shared_ptr<heavyweight_object>>
可能有显着的优势。基于容器的 std::pair<trivial_key,heavyweight_object>
由于前者的遍历仅接触键(例如 find
)与后者相比可以多缓存效率更高,后者也将获取很多大部分不需要/不相关的 heavyweight_object
字节到缓存中(当然取决于细节和数量,但实际上这种效果很容易完全淹没复制 key 的相对较小的成本)。
关于c++ - 当键是对象的一部分时最合适的关联 STL 容器 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7869014/