I need to create a list of dynamically allocated sublists; the number of sublists will be determined at runtime. I wrote some simple examples to experiment with the code. This is version1:
Code:
#include <iostream>
#include <list>
using namespace std;

int main(int argc, char **argv) {
	list<list<int>*> master;
	list<list<int>*>::iterator mIter;
	list<int>::iterator sIter;
	for(int i = 0; i < atoi(argv[1]); i++) {
		list<int>* lp = new list<int>;
		lp->push_back(i);
		lp->push_back(i+1);
		master.push_back(lp);
	}
	for(mIter = master.begin(); mIter != master.end(); mIter++) {
		for(sIter = (*mIter)->begin(); sIter != (*mIter)->end(); sIter++) {
			cout << (*sIter) << " ";
		}
		cout << endl;
	}
	cout << "finished\n";
}
It works but the pointers are cumbersome & confusing. I think it also needs changes to delete the sublists to avoid memory leaks. Then I changed it to version2:
Code:
#include <iostream>
#include <list>
using namespace std;

int main(int argc, char **argv) {
	list<list<int> > master;
	list<list<int> >::iterator mIter;
	list<int>::iterator sIter;
	for(int i = 0; i < atoi(argv[1]); i++) {
		list<int> numlist;
		numlist.push_back(i);
		numlist.push_back(i+1);
		master.push_back(numlist);
	}
	for(mIter = master.begin(); mIter != master.end(); mIter++) {
		for(sIter = (*mIter).begin(); sIter != (*mIter).end(); sIter++) {
			cout << (*sIter) << " ";
		}
		cout << endl;
	}
	cout << "finished\n";
}
This also seems to work & I think looks much nicer. But I'm a little worried about WHY it works. Why am I able to dynamically allocate the sublists without using new ? Is this the preferable way to do it? Anything special I must do to avoid losing the sublist contents if I pass the sublists to another function? Is there a better way to do this?