Maybe a vector of pointers into the other list?
Code:
#include <iostream>
#include <string>
#include <vector>
namespace Hikaru
{
using std::vector;
using std::string;
class Buyer;
class Car
{
public:
Car(const string& name): name_(name) {}
void addBuyer(Buyer* buyer) { history_.push_back(buyer); }
const vector<Buyer*>& history() { return history_; }
const string& name() { return name_; }
private:
string name_;
vector<Buyer*> history_;
};
class Buyer
{
public:
Buyer(const string& name): name_(name) {}
void addCar(Car* car) { history_.push_back(car); }
const vector<Car*>& history() { return history_; }
const string& name() { return name_; }
private:
string name_;
vector<Car*> history_;
};
void setRelation(Car& car, Buyer& buyer)
{
car.addBuyer(&buyer);
buyer.addCar(&car);
}
void showRelation(std::ostream& os, Car& car)
{
vector<Buyer*>::const_iterator iter = car.history().begin();
vector<Buyer*>::const_iterator end = car.history().end();
os << car.name() << "> ";
while (iter != end)
{
os << (*iter)->name() << ' ';
++iter;
}
os << '\n';
}
void showRelation(std::ostream& os, Buyer& buyer)
{
vector<Car*>::const_iterator iter = buyer.history().begin();
vector<Car*>::const_iterator end = buyer.history().end();
os << buyer.name() << "> ";
while (iter != end)
{
os << (*iter)->name() << ' ';
++iter;
}
os << '\n';
}
}
int main()
{
using std::cout;
using Hikaru::Car;
using Hikaru::Buyer;
std::vector<Car> cars;
std::vector<Buyer> buyers;
cars.push_back(Car("Car 1"));
cars.push_back(Car("Car 2"));
cars.push_back(Car("Car 3"));
buyers.push_back(Buyer("Buyer 1"));
buyers.push_back(Buyer("Buyer 2"));
buyers.push_back(Buyer("Buyer 2"));
// set up relationships
setRelation(cars[0], buyers[2]);
setRelation(cars[1], buyers[0]);
setRelation(cars[2], buyers[1]);
setRelation(cars[1], buyers[2]);
// show relationships
showRelation(cout, cars[0]);
showRelation(cout, buyers[1]);
showRelation(cout, cars[1]);
return 0;
}