Hello,
What is the best way in C++ to use std::map
in loops ?
- dynamically allocated
- stack allocated
Code:
for(int i=0;i<3;i++)
{
std::map<int,int>* m = new std::map<int,int>;
//or ...
std::map<int,int> m;
}
Hello,
What is the best way in C++ to use std::map
in loops ?
Code:
for(int i=0;i<3;i++)
{
std::map<int,int>* m = new std::map<int,int>;
//or ...
std::map<int,int> m;
}
That is not a static instance; a static instance would use the static
keyword (and you wouldn't be creating a new one each time through the loop).
That is a local variable.
In C++, you should always prefer to use local variables over dynamic allocation wherever possible. If you dynamically allocate an object (using new
), then you have to remember to delete it when you are done with it and you have to jump through a lot of hoops to ensure exception safety.
Avoid new
unless you really need it, i.e. the variable/structure has a lifetime unrelated to any calling scope. (If it "belongs" to the calling function, return by value.)
This is clearly not such a case. The second, preferable, example is called a local variable.
I would be making a choice between
for(int i=0;i<3;i++)
{
std::map<int,int> m;
…
}
and
std::map<int,int> m;
for(int i=0;i<3;i++)
{
…
m.clear();
}
The latter may perform better when the container is std::vector
by reusing allocated memory. With map
the difference is only style.