Reputation: 900
I have a structure as
struct Employee
{
char uName [255];
struct Employee * next;
struct Employee * prev;
};
All i want to allocate memory of 100 stucture objects at a time and then use them one by one i making a linked list.If the memory is consumed fully then again i want to allocate 100 object memory
I am doing the allocation as
struct Employee * chunk=new struct Employee[100];
Now when i want to add a new node to a linked list i want to take objects from this already allocated memory.Can somebody tell how to achieve this
Employee * pEmployeeData=NULL;
for(long int i=1;i<=100;i++)
{
pEmployeeData=EmployeePool+i;
pEmployeeData->next=NULL;
pEmployeeData->prev=NULL;
InsertAtEnd(pEmployeeData);
}
where InsertAtEnd inserts the node at the end of the linked list.Please tell how to achieve this
Upvotes: 0
Views: 1501
Reputation: 6130
I would strongly suggest that you don't try to reinvent the wheel by writing your own linked list, instead have a look at the C++ standard library which contains ready-made container types available for you to use. (for example std::vector
and std::list
).
Container types exist in the C++ standard library, and are used for storing collections of data/objects. for example, you could do something along the lines of
#include <iostream>
#include <vector>
#include <string>
struct Employee
{
std::string name;
int id;
};
int main()
{
std::vector<Employee> my_employees;
Employee fred = { "Fred", 1 };
Employee bob = { "Bob", 2 };
my_employees.push_back( fred );
my_employees.push_back( bob );
std::cout << my_employees[0].id << " " << my_employees[0].name << "\n"
<< my_employees[1].id << " " << my_employees[1].name << std::endl;
}
The standard containers are easy to use and to learn (You'll find plenty of internet resources which describe how to use them - and your book should also tell you!); If you're new to C++, then it's highly advisable to start out by figuring out how to use these before attempting to create your own.
Upvotes: 2
Reputation: 13196
You'd override the new
and delete
operators for your class.
new
would have to look at any existing pools and see if there were any free objects, and if there weren't, it would then need to allocate a pool. Then, it would return memory allocated from it.
delete
would need to check the pool that the provided object was allocated in. If ANY object is still allocated in it, the pool stays, otherwise, it can be deleted.
Also, since you're using C++, consider using a full blown class (though there is very little difference)
Upvotes: 0