vendredi 16 août 2019

Insert or push_back to end of a std::vector?

Is there any difference in performance between the two methods below to insert new elements to the end of a std::vector:

Method 1

std::vector<int> vec = { 1 };
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);

Method 2

std::vector<int> vec = { 1 };
int arr[] = { 2,3,4,5 };
vec.insert(std::end(vec), std::begin(arr), std::end(arr));

Personally, I like method 2 because it's nice and concise and inserts all the new elements from an array in one go. But is there any difference in performance? After all, they do the same thing. Don't they?

Update

The reason why I am not initialising the vector with all the elements, to begin with, is that in my program I am adding the remaining elements based on a condition.

Aucun commentaire:

Enregistrer un commentaire