I am working on homework and wanted to know what this is actually defined as:
list < NAME > * m_ofList
Where name comes from a struct
like so:
typedef struct name
{
int age;
int height;
} NAME;
I want to know what it is so I know how to insert to it or access it: push_back
, insert
, etc.
So I understand this now, but I am stuck because of some type of memory access: it produces a segmentation fault and I have been unable to figure this out. Where do I need to initialize my new list? it doesn't work in constructor or in the functions. Just FYI, it is a private list so it can only be used for member functions (i.e. m_ofList). I can produce code if anyone would like to help...
Assuming using namespace std
or using std::list
, that's a pointer to a list of objects of the class/struct NAME. To put objects in it, first you need to initialize it:
m_ofList = new list<NAME>;
or:
m_ofList = &(some already initialized list of NAME objects);
Then you can put items in it:
NAME x;
x.age = 15;
x.height = 150;
m_ofList->push_back(x);
m_ofList->insert(m_ofList->begin(), x);
If you went with dynamically allocating the list with new
, it needs to be properly disposed of when you are done with it:
delete m_ofList;
My question for you is, why is it a pointer in the first place? You could just declare it (as you should) like this:
list<Name> m_ofList;
Then you wouldn't have to worry about disposing of it. It would be taken care of by scoping rules.
Regardless of the data type you chose to hold in your list, the member functions will remain the same.
Documentation regarding what member functions you can call for the STL list container can be found here.
You can create lists that hold any data type because they are built with a construct known as templates. Templates are what allow you to create lists of different data types.
Example:
#include <list>
#include <string>
#include <cstdlib>
int main(){
//here is a list that can only hold integers
std::list<int> list1{1,2,3,4,5};
//here is a list that can only hold characters
std::list<char> list2{'a','b','c','d','e'};
//we can create a new type to represent a person
struct person{
std::string name;
int age;
int height;
person(std::string const& name_, int const& age_, int const& height_):
name(name_), age(age_) ,height(height_){}
};
//and now that we have a new person type, we can create a list to hold people
std::list<person> list3{{"John",21,70},{"Jane",20,68}};
return EXIT_SUCCESS;
}
compiled with g++ -std=c++0x -o main main.cpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With