C++ 11 vector 构造函数复制与范围?

标签 c++ c++11 vector constructor

我无法理解 vector 复制构造函数和范围构造函数的优点或区别。当我像这样构造三个 vector 时:

    vector<int> FirstVec(3, 911); //fill constructor
    vector<int> SecondVec(FirstVec.begin(), FirstVec.end()); //range constructor
    vector<int> ThirdVec(FirstVec); //copy constructor

SecondVecThirdVec的内容完全一样。在任何情况下使用其中之一有优势吗?谢谢。

最佳答案

当您想要复制不同类型容器的项目,或者不想复制整个范围时,范围构造函数非常有用。例如

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 vector 构造函数复制与范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121228/

相关文章:

c++ - 在 DLL 中使用的最简单的 C++ PUSH 通知/POST 解决方案?

c++ - while 循环和 getchar()

ubuntu - VSCode 在调试器中可视化动态数组

r - 根据字符的有序向量过滤数据帧的行

c++ - 函数执行失败后的代码 - C++

c++ - 内联调用always_inline '__m256d _mm256_broadcast_sd(const double*)'失败

c++ - 为什么左值转换有效?

c++ - std::array 复制语义

c++ - 如何从对象 vector 中删除元素?

c++ - boost (反)序列化派生对象的 vector ,使用删除函数(unique_ptr)