moonwalker
moonwalker

Reputation: 1177

C++11 vector constructor copy vs range?

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

Answers (4)

KalyanS
KalyanS

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:

  • dest. vector and src. vector will have identical sizes.
  • dest. vector storage allocation is simply for _src.size.
    • For range copy, it is end-begin+1.
  • actual copying of data is simpler too:
    • e.g. imagine a loop based copy of elements from source to destination.
    • you start from the first element of source and copy everything.
    • copy loop terminates at source vector's end, rather than range.end.

A compiler writer would probably come up with more points.

Upvotes: 1

juanchopanza
juanchopanza

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

Mike Seymour
Mike Seymour

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

user541686
user541686

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

Related Questions