inserting into a list

I have an array of pointers which are of type list defined in the following way:

list<string> * table;

How can I insert a string into an element of table? Something along the lines of:

table[5] = "new string";

I've tried:
1
2
list<string> * newPtr = &table[u];
newPtr->push_back("newString");


But that doesn't work.
I have an array of pointers which are of type list defined in the following way:


No you don't. You have a single pointer to type list<string>.

I'm guessing you probably wanted:


list<string> table ;

Assuming table then had an approriate number of elements in it:

1
2
3
4
5
6
7
const unsigned nodeToInsertBefore = 5 ;
list<string>::iterator it = table.begin() ;

for ( unsigned node = 0 ; node < nodeToInsertBefore; ++node )
     ++it ;

table.insert(it, "new string") ;


To add at the end (or tail) of the list:
table.push_back("new string");

edit: typos
Last edited on
Thanks for the reply. I actually need an array with a pointer to a list at each element. Can anyone tell me if this is how it's initialized:

list<string> * table;


followed by:
table = new list<string>[tableSize];

If it is, then how would I insert items into a given index's list?
Last edited on
Well, that's a dynamic array of list<string>.

It is not an array with a pointer to list at each element.

Assuming the above is what you want instead of what you say you want:

Use table[index] where table is used in my previous post.

table[index].push_back("new string") ;

Ok well, how would I create an array with a pointer to list at each element?
As an automatic variable:

list<string>* table[tableSize] ;

Dynamically:

list<string>** table = new list<string>*[tableSize] ;

And then, for either one, you would presumably be newing lists to point at.

1
2
for ( unsigned i=0; i<tableSize; ++i )
     table[i] = new list<string> ;


And then to add a string to the end of the list pointed to by the 2nd element of table:

table[1]->push_back("new string") ;

thanks for the help!
Topic archived. No new replies allowed.