Boost logo

Boost Users :

Subject: Re: [Boost-users] multi_index_container for composite key
From: joaquin_at_[hidden]
Date: 2010-09-09 02:01:20


Uthpal Urubail escribió:
>
> Hi
>
> I am looking for a composite key container.
>
> Though I found multi_index_container for composite key is the best I
> have few doubts in its use case:
>
> *Question:01*
>
> class Book
>
> {
>
> public:
>
> size_t mID;
>
> *size_t node[3];*
>
> };
>
> How to add the below into multi_index_container?
>
>
>
> typedef multi_index_container<
>
> Book,
>
> indexed_by<
>
> ordered_unique<
>
> composite_key<
>
> Book,
>
> member<Book,size_t,&Book::node[0]>,
>
> member<Book,size_t,&Book::node[1]>,
>
> member<Book,size_t,&Book::node[2]>
>
> >
>
> >,
>
> ordered_unique<
>
> member<Book,size_t,&Book::mID>
>
> >
>
> >
>
> > beambook;
>

member<Book,size_t,&Book::node[0]> does not work for syntactic
reasons (Book::node[0] is not a member of Book), but you can overcome this
difficulty by using a custom key extractor (http://tinyurl.com/dafk2f )
just like
this:

  template<int N>
  struct BookNodeExtractor
  {
    typedef size_t result_type;

    result_type operator()(const Book& b)const
    {
      return b.node[N];
    }
  };

  typedef multi_index_container<
    Book,
      indexed_by<
        ordered_unique<
          composite_key<
            Book,
            BookNodeExtractor<0>,
            BookNodeExtractor<1>,
            BookNodeExtractor<2>
>
>,
        ordered_unique<
          member<Book,size_t,&Book::mID>
>
>
> beambook;

> *Question:02*
>
> My requirement is straight forward. I need to get the id by providing
> 3 nodes.
>
> Should I always need to create a data structure? [class Book]
>

No, in fact you don't need to create a Book object. Suppose bb is a beambook
and you want to retrieve the mID of an element in bb with nodes n0, n1
and n2.
You only have to do the following:

  size_t mID=bb.find(boost::make_tuple(n0,n1,n2))->mID;

As you can see, you simply pass a tuple with the values for the
composite key,
not a whole Book object.

Hope this helps,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net