Skip to content

Instantly share code, notes, and snippets.

@suxue
Created October 22, 2018 11:12
Show Gist options
  • Save suxue/783115f910208ef8c41012f480eb2bc0 to your computer and use it in GitHub Desktop.
Save suxue/783115f910208ef8c41012f480eb2bc0 to your computer and use it in GitHub Desktop.
multi_index
#include <boost/flyweight.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <string>
#include <cstdint>
#include <vector>
#include <iostream>
#include <tuple>
typedef std::tuple<short, std::uint8_t, std::uint8_t> Date;
struct Cell {
Cell(const std::string& name, Date solar, Date lunar)
: name(name), solar(solar), lunar(lunar) {}
boost::flyweight<std::string> name;
Date solar;
Date lunar;
};
typedef std::tuple<boost::flyweight<std::string>, short> name_year_t;
struct lunar_year
{
typedef name_year_t result_type;
result_type operator()(const Cell& cell) const {
return std::make_tuple(cell.name, std::get<0>(cell.lunar));
}
};
std::string date_str(const Date& date)
{
using std::get;
using std::to_string;
return to_string(get<0>(date)) + "-" + to_string(get<1>(date)) + "-" + to_string(get<2>(date));
}
struct solar_year
{
typedef name_year_t result_type;
result_type operator()(const Cell& cell) const {
return std::make_tuple(cell.name, std::get<0>(cell.solar));
}
};
struct by_solar{};
struct by_lunar{};
typedef boost::multi_index::multi_index_container<
Cell,
boost::multi_index::indexed_by<
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<by_solar>,
boost::multi_index::member<Cell, Date, &Cell::solar>
>,
boost::multi_index::hashed_non_unique<
boost::multi_index::tag<by_lunar>,
boost::multi_index::member<Cell, Date, &Cell::lunar>
>,
boost::multi_index::hashed_unique<
lunar_year
>,
boost::multi_index::hashed_unique<
solar_year
>
>
> CellMulti;
int main()
{
CellMulti cells;
cells.insert({"hello", Date{1,2,2}, Date{1,2,3}});
cells.insert({"清明节", Date{2018,4,5}, Date{2018,6,1}});
auto& lunar_year_index = cells.get<2>();
auto x = lunar_year_index.find(std::make_tuple(boost::flyweight<std::string>("清明节"), 2018));
if (x == lunar_year_index.end()) {
} else {
std::cout << x->name << " " << date_str(x->solar) << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment