Re: std::map and insert()
dragoncoder wrote:
I have the following code. Plesae have a look.
#include <iostream>
#include <string>
#include <map>
#include <cstdlib>
using namespace std;
typedef map<int,string, less<int> > INT2STRING;
INT2STRING::iterator theIterator;
It's a BAD IDEA(tm) to define things like iterators in the global scope.
int main(int argC,char ** argV)
If you're not going to use 'argC' or 'argV', why declare them?
{
INT2STRING * pmap = NULL;
pmap = new INT2STRING;
Why are the two lines split? Why can't you initialise 'pmap' to the
result of the 'new' expression right where you defined it?
//pmap = static_cast<INT2STRING*>(malloc(sizeof(INT2STRING)));
for(int i =0;i<10;i++)
{
string buff = "Buffer";
pmap->insert(INT2STRING::value_type(i,buff));
}
for(int i=0;i<10;i++)
{
theIterator = pmap->find(i);
If you drop the global declaration of 'theIterator', you could simply
define it here. Remember, the tighter the scope of an object, the better.
if(theIterator != pmap->end() ) cout << (*theIterator).second<<
"\n";
else cout << "[err] ";
}
if (pmap != NULL) delete pmap;
Deleting a null pointer is a NOP. There is no need to check if it's
NULL or not, just delete.
//if (pmap != NULL) free (pmap);
}
The code runs perfectly fine. But if I change the new call to malloc()
and delete to free(), I get a segmentation fault ( I am expecting the
problem at the call to insert() ).
Is it necessary to create the map using new only? Can someone please
quote the section of standard which does not allow this to happen.
'new' doesn't just allocate memory. It creates the object. 'delete'
doesn't just release the memory, it destroys the object. Objects need
to be created (constructed) before they can be used.
What book are you reading that doesn't explain that?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask