Boost logo

Boost Users :

Subject: Re: [Boost-users] [MultiIndex] Indexing integers
From: Joaquin M Lopez Munoz (joaquin_at_[hidden])
Date: 2014-07-09 06:40:47


Sensei <senseiwa <at> gmail.com> writes:

>
> Dear all,
>
> I am experimenting with MultiIndex, and I am happy with my custom classes.
>
> Now I am wondering, can I index integers without a custom class?
>
> For instance, say we have a 32 bit unsigned integer, how can I index
> these with respect to the MSB or LSB? [...]

You can define a function that does the MSB/LSB extraction and either
pack it as a custom key extractor:

http://www.boost.org/libs/multi_index/doc/
tutorial/key_extraction.html#user_defined_key_extractors

or plug it into boost::multi_index::global_fun:

http://www.boost.org/libs/multi_index/doc/
tutorial/key_extraction.html#global_fun

The following example shows the latter approach for a multi_index_container
of uint32_t's --you can easily adapt this to your particular scenario
where the uint32_t's are members of a larger class.

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/global_fun.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <cstdint>
#include <iostream>

using namespace boost::multi_index;

inline uint16_t ls16half(uint32_t n)
{
  return static_cast<uint16_t>(n&0xFFFFul);
}

inline uint16_t ms16half(uint32_t n)
{
  return static_cast<uint16_t>(n>>16);
}

typedef multi_index_container<
  uint32_t,
  indexed_by<
    ordered_non_unique<global_fun<uint32_t,uint16_t,ls16half>>,
    ordered_non_unique<global_fun<uint32_t,uint16_t,ms16half>>
>
> multi_t;

int main()
{
  multi_t m={0x00030000ul,0x00020001ul,0x00010002ul,0x00000003ul};
  
  std::cout<<std::hex;
  for(auto n:m.get<0>())std::cout<<n<<" ";
  std::cout<<"\n";
  for(auto n:m.get<1>())std::cout<<n<<" ";
  std::cout<<"\n";
}

Joaquín M López Muñoz
Telefónica


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