読者です 読者をやめる 読者になる 読者になる

Boost.MultiIndexでゲッターをキーとした並び順

C++

<boost/multi_index/mem_fun.hpp>のconst_mem_funを使います。

#include <iostream>
#include <string>
#include <algorithm>
#include <boost/mem_fn.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

using namespace boost::multi_index;

class person {
    int id;
    std::string name;
    int age;
public:
    person(int id, const std::string& name, int age)
        : id(id), name(name), age(age) {}

    const std::string& get_name() const
        { return name; }

    void print() const
        { std::cout << id << "," << name << "," << age << std::endl; }
};


typedef multi_index_container<
    person,
    indexed_by<
        ordered_unique<const_mem_fun<person, const std::string&, &person::get_name> >
    >
> container;


int main()
{
    container c;
    c.insert(person(1, "Millia", 20));
    c.insert(person(3, "Akira",  30));
    c.insert(person(4, "Johnny", 10));

    std::for_each(c.begin(), c.end(), boost::mem_fn(&person::print));
}
3,"Akira",30
1,"Johnny",10
4,"Millia",20