use
IAF.clear()
NBM.clear()
WCR.clear()
(Edit: references to the spec and caveats)
Note that if you're storing pointers, clear()
will remove the pointers, but it will not delete the memory pointed to by the pointers.
Pregunta
Hi i am doing my homeworks and i have a problem.
I need diferents maps and set in the application and i want reuse some variables. I have this global variables
map<char,set<char> > IAF; //I Am Father
map<char,int> NBM; //Number Before Me
set<char> WCR; //Who can run
and every time in the main i need reset this variables.
I have done two things:
IAF = new map<char,set<char> >;
and
IAF = map<char,set<char> >;
But any has run.
Can someone help me?
Solución
use
IAF.clear()
NBM.clear()
WCR.clear()
(Edit: references to the spec and caveats)
Note that if you're storing pointers, clear()
will remove the pointers, but it will not delete the memory pointed to by the pointers.
Otros consejos
map<char,set<char> > IAF;
This is a definition of variable. This is not a pointer. If you want to do some kind of initialization you can use one of supported methods, e.g:
std::copy( differentContainer.begin(), differentContainer.end(), IAF.begin());
or
while( ...) {
IAF.insert( ...);
// or
IAF[ key] = value;
}
To delete the content of map you can do (this will not automatically delete memory pointed to by pointer in map - if you store pointers, use a smart pointers then):
IAF.clear();
In addition to the previous answers which are fairly clear. The new
keyword, that you used at some point, is to allocate memory for a pointer.
map<char, set<char> > *IAF = new map<char, set<char> >;
//...
// free the memory
delete IAF;
Check the Dynamic memory allocation for more information and to understand when and how to use pointers.
Also, using
IAF = map<char,set<char> >;
Is incorrect. The map<char, set<char> >
is a class name (combined with templates generic programming, see the answer to What is the meaning of "generic programming" in c++? ) and hence you cannot assign it to a variable in this way. What you want to do is to call the constructor that will return an instance of that class:
IAF = map >();
However, doing it this way is not efficient at all. It creates a temporary object, destroys IAF
, copies the temporary, and then destroys the temporary (unless you are using C++11 and in this case you use move
, but still...). So, it's better to use the clear()
as stated by the other answers.