我完全同意杰瑞的回答。例如,如果您尝试对图进行建模,请考虑使用邻接列表、边列表或矩阵表示。
Paul 的回答有点随意,所以,这里有一个使用 Boost Multi Index 的示例:
住在科利鲁
#include <iostream>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/ordered_index.hpp>
struct T1 {
std::string name;
bool operator<(T1 const& o) const { return name < o.name; }
};
struct T2 {
int id;
bool operator<(T2 const& o) const { return id < o.id; }
};
namespace bmi = boost::multi_index;
struct Relation {
T1 const* key1;
T2 const* key2;
std::string const& name() const { return key1->name; }
int id () const { return key2->id; }
friend std::ostream& operator<<(std::ostream& os, Relation const& r) {
return os << "(" << r.name() << ", " << r.id() << ")";
}
};
using RelationTable = bmi::multi_index_container<Relation,
bmi::indexed_by<
bmi::ordered_unique<bmi::tag<struct by_composite>,
bmi::composite_key<Relation,
bmi::const_mem_fun<Relation, std::string const&, &Relation::name>,
bmi::const_mem_fun<Relation, int, &Relation::id>
>
>
> >;
#include <set>
int main() {
using namespace std;
set<T1> set1 { {"A"}, {"B"}, {"C"} };
set<T2> set2 { {1}, {2}, {3}, {4} };
// convenient data entry helpers
auto lookup1 = [&set1](auto key) { return &*set1.find(T1{key}); }; // TODO error check?
auto lookup2 = [&set2](auto key) { return &*set2.find(T2{key}); };
auto relate = [=](auto name, auto id) { return Relation { lookup1(name), lookup2(id) }; };
// end helpers
RelationTable relations {
relate("A", 1), relate("A", 3),
relate("B", 1), relate("B", 4),
relate("C", 1), relate("C", 3), relate("C", 4),
};
for (auto& rel : relations)
std::cout << rel << " ";
}
印刷
(A, 1) (A, 3) (B, 1) (B, 4) (C, 1) (C, 3) (C, 4)