Create and maintain shared objects among containers

Hi, let's say I already have 2 class BusStop and BusService implemented as follows:

1
2
3
4
5
6
7
8
class BusStop {
private:
	string roadName;
	string busStopNumber;
public:
	BusStop();
	BusStop(string roadName, string busStopNumber);
};


1
2
3
4
5
6
7
8
class BusService {
private:
	string busServiceNumber;
        list<BusStop*> busStopList;
public:
	BusService();
	BusService(string busNumber, list<BusStop*> busStopList);
};


And here's a snippet from the main program to read and store data from user's input (minor details like variable declarations and what not are omitted)

1
2
3
4
5
6
7
8
9
list<BusService> busServiceList;
for(int i = 0; i < numOfServices; ++i){
        list<BusStop> bsList;
        for(int i = 0; i < numOfStops; ++i){
                BusStop *bs = new BusStop(roadName, busNumber);
                bsList.push_back(bs);
        }
BusService bService(serviceNum, bsList);
busServiceList.push_back(bService);}


However, since a bus stop may be shared among different bus services, there may be duplicate copies of a BusStop object. That's what I want to avoid because the program, after storing data to BusStop and BusService objects, is also expected to display all bus stops on a given roadName.

Is there any workaround to avoid redundant BusStop objects, as in how to make the pointers in different BusService point to the same BusStop? Any help is much appreciated, thanks!
Last edited on
Have a single container of [smart]pointer to all bus stops. Modify bus stot to hold numbers of all buses which stops on it. And initialise BusServices with pointers to objects contained in big container

http://puu.sh/bYNc3/39bf423554.png
Hi, thanks for your suggestion, but I'm still baffled as how to proceed further from there. Does that mean we have to create another list<BusStop> that holds all bus stops? If that's the case then how can we ensure that these bus stops are distinct?

For example user input is assumed to have following format
1
2
3
4
5
6
7
8
9
10
11
2 //Number of bus services to be created
1A //1st bus service
1 //Number of bus stops under the 1st bus service
Road1 //Road name
00001 //Bus number
2A//2nd bus service
2//Number of bus stops under the 2nd bus service
Road1 //line x
00001
Road2
00002


How can we avoid creating another BusStop object when we read line x?
Last edited on
Check if stop already exist in list before adding it.
Topic archived. No new replies allowed.