c++ - 为什么在 std::copy 期间使用 std::back_inserter 而不是 end()?
问题描述
我见过std::copy()
使用std::back_inserter
,但我使用过std::end()
,两者都有效。我的问题是,如果工作正常,为什么std::back_inserter
需要std::end()
?
#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的典型表现。
推荐阅读
- mysql - 如何使用 Entity Framework 6 MySQL 更新记录
- jenkins - 使用 deleteDir 的 Jenkins 管道“无法删除”
- javascript - 如何附加谷歌街景图像?
- android - 一个地理围栏用于多个标记
- scala - Scala抽象类实例
- java - 如何根据行项目的属性设置 TableCell 样式?
- python - Pandas 数据框的动态合并
- node.js - 在 MEAN Stack 应用程序中重新加载页面后无法获取 /page
- javascript - 无效输入后如何设置 DOM 样式?
- c++ - 在 C++ 中寻找吃得最少的人