structures inside STL List

Hello im a newbie in C++ programming.. Pls Help...

I declared a structure

struct mystruct{
firstname[20];
lastname[20];
};

then i defined a list with that type mystruct

list<mystruct> names;

is this correct? I compiled the program, got no errors... tried finding ways to add names via the STL list "names" ... pls help...thanks!

if its not too much, sorting the list by firstname or lastname would be a very big help tooo.....
Hi, yes, that is basically correct.

See the site tutorial (http://www.cplusplus.com/reference/stl/list/ ) for more docs on list, which should give you the answers you need:-)
Last edited on
Remove the trailing ) that got tacked on, it confused me for a second XD.

From looks of it you will need to use an iterator to access the elements. Just define the iterator using the "begin" one and use that as your current position in the list.
Hmm big thanks to ur suggestions. The Docs available from http://www.cplusplus.com/reference/stl/list/ is only limited adding elements if the list is declared as int or string.. Im confused how to add a whole bunch of structured data in the list.. name and firstname...or :(
Because list is a Template class, the code is the same regardless of what you are putting in the list.

So if you have

list<mystruct> names;

and

1
2
3
mystruct aName;
aName.firstname = "Jon";
aName.lastname = "Smith";


to add this to the end list you just use

 
mystruct.push_back(aName);

wow thanks a lot Faldrax.. Ive finally figured it out.. i only have to use iterator to access the list elements of struct
heres my code

struct mystruct {
char name[20];
int grade;
};
int main ()
{
int i;
list<mystruct> mylist;
mystruct names;
list<mystruct>::iterator it;
for (i=0;i<5;i++) {
strcpy(names.name, "Jude");
names.grade = i+78;
mylist.push_back(names);
}
it = mylist.begin();
while (it != mylist.end()) {
cout << "Name: " << it->name << " Grade: " << it->grade << endl;
it++;
}
system("PAUSE");
return 0;
}
Topic archived. No new replies allowed.