0

对于以下代码:

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->firstName”来获取 char* 进行比较,因为该值不再是一个结构,它只是一个双精度值。那么我在哪里可以得到用于比较的字段?有类似 k.get<0>() 的东西吗?

4

1 回答 1

1

复合键的比较标准通过 指定composite_key_compare。在您的特定情况下,您需要类似

ordered_unique<
  comp_key,
  composite_key_compare<
     std::less<double>,
     CompareLess,
     Compareless
  >
>

whereCompareLess只需要用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.

于 2013-07-16T14:43:26.623 回答