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;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Avoid
newunless 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
and
The latter may perform better when the container is
std::vectorby reusing allocated memory. Withmapthe difference is only style.