Page 1 of 1

nested lists

Posted: 12 Dec 2005, 01:57
by krogothe
Say i want to make nested lists but im nesting arrays of lists like these:

Code: Select all

	ground_factories = new list<int>[numOfSides];
	sea_factories = new list<int>[numOfSides];
	ground_defenses = new list<int>[numOfSides];
The above were all initialized, declared etc properly and work. Now i want to stick those lists in one bigger list (having each list, eg ground_factories as an element)

I looked up in the internet and found nothing related to this :( so i tried things like:

Code: Select all

	list<list<int>>	*all_lists;
	all_lists = new list<list<int>>;
	all_lists.push_back(ground_factories);
I get an error:

Code: Select all

.\UnitTable.cpp(37) : error C2228: left of '.push_back' must have class/struct/union
        type is 'std::list<_Ty> *'
        with
        [
            _Ty=std::list<int>
        ]
        did you intend to use '->' instead?
How would i implement this?

Posted: 12 Dec 2005, 03:01
by SoftNum
Try

Code: Select all

all_lists->push_back(ground_factories); 
But, I would make all_lists not a pointer.

Posted: 12 Dec 2005, 04:10
by mr sharpoblunto
This code should be what your after.

Code: Select all

ground_factories = new list<int>(5);
sea_factories = new list<int>(5);
ground_defenses = new list<int>(5); 
   
list<list<int> *>   all_lists;//stores pointers to the nested lists

all_lists.push_back(ground_factories);
all_lists.push_back(sea_factories);
all_lists.push_back(ground_defenses);

also be sure to free up the memory assigned to these lists when your finished to prevent memory leaks

Code: Select all

     for (list<list<int> *>::iterator iter=all_lists.begin();iter!=all_lists.end();++iter)
    	delete (*iter);

Posted: 12 Dec 2005, 04:15
by krogothe
mr sharpoblunto, thank you! that works just fine!
man its sooo good to have so many pro c++ programmers to help me!
ill go off to make pretty trees now!

Posted: 12 Dec 2005, 18:19
by jcnossen
Storing pointers to the list is not really necessary in this case though, then you don't have to delete them after:

Code: Select all

list<list<int> > all_lists;

all_lists.push_back(list<int>());
list<int> *ground_factories=&all_lists.back();

all_lists.push_back(list<int>());
list<int> *sea_factories=&all_lists.back();

all_lists.push_back(list<int>());
list<int> *ground_defenses=&all_lists.back();

Posted: 12 Dec 2005, 19:00
by krogothe
any advantages in speed over either method?

Posted: 12 Dec 2005, 19:24
by jcnossen
if any difference, the last method is faster mainly because you're calling the memory manager less often.