I have an array, say ARR, and the total number of objects in ARR is known.
I want to copy (put) an attribute of each object in ARR into an STL vector, say VEC.
One way is to iterate through ARR
VEC.pushback(ARR[i].att);
The other way is
VEC.resize(ARR.size());
VEC[i] = ARR[i].att;
Do them make difference regarding runtime performance? Which one is better? Thanks.
FOLLOW-UP: I would like to provide some experiment results for anyone interested.
I tried (1) resize() + ‘=’ and (2) reserve() + push_back() methods by putting 50000 integers into an STL vector.
(1) takes 0.000201s;
(2) takes 0.000229s.
- Both were compiled with g++ -O3, and I ran the program several times.
- (1) outperforms (2) consistently.
- (1) has extra allocations, thus taking slightly more memory in terms of space.
Calling
resize()(orreserve()) before may potentially save some resizing as you add new items. Anyway, you already know the number of items, so it makes even more sense.With
resize()you will have a default construct step, I’d go withreserve()to prevent reallocations andpush_back()(and in C++11,emplace_back()if your compiler supports it)