c++boostboost-multi-index

Is it possible to have boost multi_index container index one element with 2 key values?


I want to have my boost multi_index container index one element with multiple key values on the same index. Is that possible?

struct Student {
    int Id;
    std::unordred_set<std::string> Clubs;
};

Suppose this student belongs to Technology and Movie clubs, and I have unique hashed index on Id and non_unique hashed index on clubs (I want to know what students are in each club by looking at club name).

I want to be able to find the same student by searching for either "Technology" or "Movie" using boost multi_index. Is it possible with boost or do I need to roll my own data store?


Solution

  • You can't do it with a multi_index containing your Student type, but you can use (something based on it) with a different type.

    using Id_t = int;
    using Club_t = std::string;
    using StudentClubs = boost::bimap<boost::bimap::multiset_of<Id_t>, boost::bimap::multiset_of<Club_t>>;
    
    StudentClubs student_clubs = /* some data */;
    

    You can then lookup all the students in the movie club

    for (auto [club, student] : boost::iterator_range(student_clubs.right.equal_range("movie"))) {
        std::cout << student;
    }
    

    Or all the clubs that student 3 is in

    for (auto [student, club] : boost::iterator_range(student_clubs.left.equal_range(3))) {
        std::cout << club;
    }