C ++ 11向量构造函数副本与范围? [英] C++11 vector constructor copy vs range?
本文介绍了C ++ 11向量构造函数副本与范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不了解矢量拷贝构造函数和范围构造函数的优点或区别。当我构建如下三个向量时:
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
SecondVec
的内容和 ThirdVec
完全相同。在任何情况下使用其中之一具有优势?谢谢。
The contents of SecondVec
and ThirdVec
are exactly the same. Are there any scenarios in which using one of them has advantages? Thank you.
推荐答案
如果要复制其他类型容器的项目,或者不要复制容器,则范围构造函数非常有用。不想复制整个范围。例如
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);
这篇关于C ++ 11向量构造函数副本与范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文