If you are able to, is it more efficient to set the size of a vector up front? I intend to push_back values.
Share
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.
If you are using
.push_back()to store values, it is incorrect to “set the size of the vector up front” using the.resize()member function. Rather, you would set the capacity of the vector up front using the.reserve()member function.Here are three correct approaches:
Yes, the 2nd approach is usually more size- and time-efficient than the first.
The 2nd approach is sometimes more time-efficient than the 3rd. Or not. You should measure it to see if it even matters.