I need to insert onto the end of a vector, 2 elements each time.
I was wondering whether doing vector.insert( iter_first, iter_second) is faster than doing vector.push_back( first ) then vector.push_back( second )?
Maybe another alternative would be to create a struct like this:
struct T{int a; int b;};
T t;
t.a = first;
t.b = second;
X.push_back(t);
If the two elements are logically related, then you would use a struct or class. If they're unrelated then certainly don't group them for performance reasons.
This smells of premature optimization. Instead, write the code that's clearest to maintain and let the compiler generate the code for you. That's what it's there for. Consider that code that's easy to read is easy to maintain, and code that's easy to maintain is easy to refactor and less likely to have subtle performance bugs due to misunderstandings.
While in your case the difference is insignificant, in general the C++ language standard specifies complexity information, so you don't need to ask - you can just look it up. vector::push_back has amortized constant time complexity, and vector::insert is either proportional to the sum of the number of elements inserted and the number of elements moved, or the product of the two, depending on how you call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With