Reputation: 1177
I can't understand the advantages of or differences between vector copy constructors and range constructors. When I construct three vectors like this:
vector<int> FirstVec(3, 911); //fill constructor
vector<int> SecondVec(FirstVec.begin(), FirstVec.end()); //range constructor
vector<int> ThirdVec(FirstVec); //copy constructor
The contents of SecondVec
and ThirdVec
are exactly the same. Are there any scenarios in which using one of them has advantages? Thank you.
Upvotes: 8
Views: 10218
Reputation: 527
There is another important consideration, in addition to the answers above, if you care for the last CPU cycle and code byte.
When you use the copy constructor, it gives full freedom to the library method to work with the full source vector.
With the range-specifier, the method has to perform more checks and becomes generalized. As you can easily imagine, end of the range may not be the same as the end of the source vector.
Let's assume that we are developing the library code and see what are the differences:
A compiler writer would probably come up with more points.
Upvotes: 1
Reputation: 227400
The range constructor is quite useful when you want to copy the items of a different type of container, or don't want to copy a full range. For example
int a[] = {1,2,3,4,5};
std::set<int> s{3, 911};
std::vector<int> v0{1,2,3,4,5};
std::vector<int> v1(std::begin(a), std::end(a));
std::vector<int> v2(a+1, a+3);
std::vector<int> v3(s.begin(), s.end());
vector<int> v4(v0.begin(), v0.begin() + 3);
Upvotes: 17
Reputation: 254461
The range constructor is more generic; you can provide any valid sequence of suitable elements, not necessarily from the same type of container, or spanning a whole container, or even from a container at all.
The copy constructor is simpler and potentially more efficient; but is only suitable when you want to copy the entirety of another vector.
So use the copy constructor when you want to copy the same kind of container, as you do here; and the range constructor for more general ranges.
Upvotes: 5
Reputation: 210445
I believe the allocator is copied in one case but not in the other.
In general, if you want to make a copy of a vector then you should copy the vector.
Upvotes: 0