Elaborating on Sehe's answer, this is a realization of the relation table idea using Boost.Flyweight to hold the individual entities:
Live Coliru Demo
#include <boost/flyweight.hpp>
#include <boost/flyweight/key_value.hpp>
#include <boost/flyweight/no_tracking.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/key.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>
#include <string>
#include <utility>
using namespace boost::flyweights;
using namespace boost::multi_index;
struct student_impl
{
student_impl(
int id,const std::string& name="",const std::string& surname=""):
id{id},name{name},surname{surname}{}
int id;
std::string name;
std::string surname;
};
using student=flyweight<
key_value<int,student_impl,key<&student_impl::id>>,
no_tracking
>;
using club=flyweight<std::string>;
static student::initializer sinit;
static club::initializer cinit;
using club_student_row=std::pair<club,student>;
using club_student_table=multi_index_container<
club_student_row,
indexed_by<
hashed_non_unique<key<&club_student_row::first>>,
hashed_non_unique<key<&club_student_row::second>>
>
>;
club_student_table club_student;
template<typename Student,typename... Strs>
void add_to_clubs(const Student& s,const Strs&... strs)
{
(club_student.emplace(strs,s),...);
}
void print_students_in_club(const club& c)
{
std::cout<<c<<": ";
for(const auto& [_,s]:
boost::make_iterator_range(club_student.equal_range(c))){
std::cout<<s.get().name<<" "<<s.get().surname<<"; ";
}
std::cout<<"\n";
}
void print_clubs_for_student(const student& s)
{
std::cout<<s.get().name<<" "<<s.get().surname<<": ";
for(const auto& [c,_]:
boost::make_iterator_range(club_student.get<1>().equal_range(s))){
std::cout<<c<<"; ";
}
std::cout<<"\n";
}
int main()
{
add_to_clubs(student_impl(1,"Ben"),"Technology");
add_to_clubs(student_impl(2,"Caleth"),"Technology","Movie");
add_to_clubs(student_impl(3,"Sehe"),"Technology","Latin");
add_to_clubs(student_impl(4,"Joaquin","Lopez"),"Movie","Latin");
print_students_in_club(club("Technology"));
print_clubs_for_student(student(4));
}
Output
Technology: Sehe ; Caleth ; Ben ;
Joaquin Lopez: Latin; Movie;