Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which function is faster push_back, insert in C++

Tags:

c++

visual-c++

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);
like image 400
mona Avatar asked Apr 22 '26 03:04

mona


2 Answers

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.

like image 179
Mark B Avatar answered Apr 24 '26 17:04

Mark B


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.

like image 41
Raymond Chen Avatar answered Apr 24 '26 18:04

Raymond Chen