为什么在 std::copy 中使用 std::back_inserter 而不是 end()
Why use std::back_inserter instead of end() during std::copy?
我见过std::copy()
使用std::back_inserter
但我使用了std::end()
并且两者都有效。我的问题是,如果std::end()
工作很好,为什么还需要std::back_inserter
?
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
// Declaring first container
vector<int> v1 = { 1, 2, 3 };
// Declaring second container for
// copying values
vector<int> v2 = { 4, 5, 6 };
// Using std::back_inserter inside std::copy
//std::copy(v1.begin(), v1.end(), std::back_inserter(v2)); // works
std::copy(v1.begin(), v1.end(), v2.end()); // also works
// v2 now contains 4 5 6 1 2 3
// Displaying v1 and v2
cout << "v1 = ";
int i;
for (i = 0; i < 3; ++i) {
cout << v1[i] << " ";
}
cout << "nv2 = ";
for (i = 0; i < 6; ++i) {
cout << v2[i] << " ";
}
return 0;
}
第一个将值插入向量,另一个是未定义的行为,它将项目写入刚过向量末尾的位置。
尝试打印生成的矢量:
std::copy(v1.begin(), v1.end(), std::back_inserter(v2)); // works
for (auto x : v2) cout << " " << x;
cout << endl;
指纹
4 5 6 1 2 3
而
std::copy(v1.begin(), v1.end(), v2.end());
for (auto x : v2) cout << " " << x;
cout << endl;
指纹
4 5 6
(在调试模式下引发断言失败)
它在您的特定编译器中为您工作的事实并不能使其正确。看似工作是UB的典型表现。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 使用back_inserter()或inserter()提高std::copy()的效率
- 为什么std::inserter这么慢
- 我可以一直使用std::inserter(container,container.end())而不是std::back_
- 对std::inserter对std::set使用.begin()和.end()有区别吗?