以下代码:
struct MyStruct
{
char* firstName;
char* secondName;
int age;
};
typedef composite_key
<MyStruct*,
BOOST_MULTI_INDEX_MEMBER(MyStruct, char*, firstName),
BOOST_MULTI_INDEX_MEMBER(MyStruct, char*, secondName)
> comp_key;
typedef multi_index_container
<
MyStruct*,
indexed_by
<
ordered_unique
<
comp_key,
CompareLess
>
>
> MyContainer;
我可以轻松地编写一个无比的,如下所示:
struct CompareLess
{ // functor for operator<
static inline int compare(const char* left, const char* right)
{
return strcmp(left, right);
}
inline bool operator()(const char* left, const char* right) const
{ // apply operator<= to operands
return compare(left, right)<0;
}
static inline int compare(const boost::tuple<char*>& x, const char*y)
{
return compare(x.get<0>(),y);
}
inline bool operator()(const boost::tuple<char*>& x, const char*y) const
{
return compare(x,y)<0;
}
static inline int compare(const boost::multi_index::composite_key_result<comp_key>& k, const boost::tuple<char*>& y)
{
return -compare(y,(const char*)(k.value->firstName));
}
inline bool operator()(const boost::multi_index::composite_key_result<comp_key>& k, const boost::tuple<char*>& y) const
{
return compare(k,y)<0;
}
static inline int compare(const boost::tuple<char*>& y, const boost::multi_index::composite_key_result<comp_key>& k)
{
return compare(y,(const char*)(k.value->firstName));
}
inline bool operator()(const boost::tuple<char*>& y, const boost::multi_index::composite_key_result<comp_key>& k) const
{
return compare(y,k) <0;
}
}
但是当我想写下面的内容时:
typedef composite_key
<double,
char*,
char*
> comp_key;
我在使用以下函数
编写compareLess时遇到问题 static inline int compare(const boost::tuple<char*>& y, const boost::multi_index::composite_key_result<comp_key>& k)
{
return compare(y,(const char*)(k.value->firstName));
}
我不知道如何编写一些代码作为“k.value-&gt; firstName”来获取用于比较的char *,因为该值不再是结构,它只是一个double。那么我在哪里可以进行比较呢?有什么像k.get&lt; 0&gt;()?
答案 0 :(得分:1)
复合键的比较条件通过composite_key_compare
指定。在您的特定情况下,您需要类似
ordered_unique<
comp_key,
composite_key_compare<
std::less<double>,
CompareLess,
Compareless
>
>
其中CompareLess
只需使用const char*
s:
struct CompareLess
{
static inline int compare(const char* left, const char* right)
{
return strcmp(left, right);
}
inline bool operator()(const char* left, const char* right) const
{
return compare(left, right)<0;
}
};
脚手架的其余部分由composite_key_compare
提供。