我創建了一個類Route
,我想將其存儲在std::set
中。一個路由索引的Id,所以我想要的是能夠有一個像在自定義比較器中查找std :: set中的元素
class RouteTemplate
{
Route *RouteTemplate::getRoute(const char *pId);
Route::ptr_set mRoutes;
};
Route *RouteTemplate::getRoute(const char *pId)
{
Route::ptr_set::const_iterator pos = mRoutes.find(pId);
if(pos == mRoutes.end())
return NULL;
return *pos;
}
然而,我得到一個編譯器錯誤。
conversion from 'const char *' to 'Route *const ' not possible
據我所知,我必須實施比較,我做了。
class Route
{
public:
static const size_t _id_len = 11;
class comparator
{
public:
bool operator() (const Route &oLeft, const Route &oRight) const
{
return oLeft < oRight;
}
};
class ptr_comparator
{
public:
bool operator() (const Route *oLeft, const Route *oRight) const
{
return (*oLeft) < (*oRight);
}
};
typedef std::set<Route, Route::comparator> set;
typedef std::set<Route *, Route::ptr_comparator> ptr_set;
public:
Route(void);
Route(const char *oId);
virtual ~Route(void) {};
inline bool operator<(const Route &oOther) const
{
return strncmp(mId, oOther.mId, _id_len) < 0;
}
inline bool operator<(const char *oId) const
{
if(!oId)
return false;
return strncmp(mId, oId, _id_len) < 0;
}
inline const char *getId(void) const { return mId; }
inline void setId(const char *oId)
{
if(oId == NULL)
mId[0] = 0;
else
{
strncpy(mId, oId, sizeof(mId));
mId[_id_len] = 0;
}
}
private:
char mId[_id_len+1];
// Additional members
};
['的std :: find_if'](http://en.cppreference.com/w/cpp/algorithm/find ) – Biffen
...但問題是什麼?! – Biffen
@Biffen:'find_if'將是'O(n)',而理論上可以在'O(log n)' – Jarod42