【发布时间】:2011-02-18 21:02:37
【问题描述】:
我似乎无法弄清楚在容器中查找结构的语法。
我有一组 Event 结构。我试图通过搜索其键来找到这些结构之一。我得到下面注释的编译器错误。
struct Event {
public:
bool operator < ( const Event & rhs ) const {
return ( time < rhs.time );
}
bool operator > ( const Event & rhs ) const {
return ( time > rhs.time );
}
bool operator == ( const Event & rhs ) const {
return ( time == rhs.time );
}
double time;
int eventID;
int hostID;
int s;
};
typedef std::multiset< Event, std::less< Event > > EventPQ;
EventPQ currentEvents;
double oldRecTime = 20.0;
EventPQ::iterator ceItr = currentEvents.find( EventPQ::key_type( oldRecTime ) ); // no matching function call
我尝试了一些排列都无济于事。我认为定义条件相等运算符就足够了。
解决方案
在更正我的错字后(抱歉),我现在有了一个最接近 AraK 的解决方案,并由 Soapbox 建议使用的 explicit 增强:
struct Event {
explicit Event(double t) : time(t), eventID(), hostID(), s() {}
Event(double t, int eid, int hid, int stype) : time(t), eventID( eid ), hostID( hid ), s(stype) {}
...
};
EventPQ::iterator ceItr = currentEvents.find( EventPQ::key_type( Event(oldRecTime) ) );
我最近发现另一种选择是使用find_if,讨论了here。
感谢您的帮助。
【问题讨论】:
-
唯一需要的运算符是
operator <,其他都是多余的; a>b 与 b 相同