Reputation: 5657
Let's say I have a vector of 10 ints and I want to create 2 subvectors each of 5 elements.
Is it faster if I slice the vector like this:
vector<int> vec({0,1,2,3,4,5,6,7,8,9});
auto x = vec.begin();
vector<int> vec2(x, x+5);
x += 5;
vector<int> vec3(x, x+5);
As opposed to this?
vector<int> vec({0,1,2,3,4,5,6,7,8,9});
vector<int> vec2;
for (int i = 0; i < 5; i++) {
vec2.push_back(vec[i]);
}
vector<int> vec3;
for (int i = 5; i < 10; i++) {
vec3.push_back(vec[i]);
}
Upvotes: 1
Views: 211
Reputation: 2888
First will be faster, because in the first way std::vector
will allocate all needed memory in first construction, but in second way with std::vector<T>::push_back
need to allocate memory and increase the underlying array size which is painful.
Here is a little benchmark: https://quick-bench.com/q/dXoWJhTzYDgNnIPFj-vla4pZ_PU
Upvotes: 4