Let’s say I have a vector<string> containing “a” and “b”, I wanna copy itself 2 times so that the vector now contains “a”, “b”, “a”, “b”, “a”, “b”
What is a better approach than using for and push_back?
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.
My initial thought:
thanks to Emilio Garavaglia for first pointing out problems with this, see here many reasons why this has problems: Does std::vector::insert() invalidate iterators if the vector has enough room (created through reserve)?
Second try:
since no implementation is going to implement a std::string whos default constructor allocates something on the heap this should cause less heap access and therefore be faster than others examples.
Another heap access minimization is to copy the vector into another insert it and then move in the originals, I stole Emilio Garavaglia code and pimped it: