When using STL containers (such as map, list, vector, etc.), whether to put an object or an object pointer, that is, vector<int> or vector<int*>, where the vector can be replaced by other containers, int can be replaced with other basic types, or a custom data structure or class.
First of all, to illustrate, these two ways, how to use the function can be achieved, a group of integers into the container. First look at the difference between the two ways in use.
1.vector<int>
Copy Code code as follows:
Vector<int> vectemp;
for (int i=0; i< i++)
{
Vectemp.push_back (i);
}
This method does not require dynamic new memory, and of course it does not have to delete.
2.vector<int*>
Copy Code code as follows:
Vector<int*> vectemp;
for (int i=0; i< i++)
{
int* ntemp = new int;
Ntemp = &i;
Vectemp.push_back (i);
}
This approach uses new, and of course, delete:
Copy Code code as follows:
Std::vector<int*>::iterator Iter;
For (Iter=vectemp.begin (); Iter!=vectemp.end (); iter++)
{
int* temp = *iter;
Delete temp;
temp = NULL;
}
3. The difference between two usages:
1 vector<int> do not need dynamic operation of memory, do not worry about memory leaks and other issues;vector<int*> to note that new and delete in pairs.
2 when the int changed into other types or structures or classes, with vector<int*> this way is more convenient, the contents of the container to occupy less memory, the pointer in use, to apply for space, not, that is a 4-byte address.