C++11 vector constructor copy vs range?

Deadly 提交于 2019-12-22 06:59:52

问题


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.


回答1:


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);



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/30121228/c11-vector-constructor-copy-vs-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!