【发布时间】:2019-01-21 20:54:22
【问题描述】:
我见过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(), v2.begin());?使用v2.end()是未定义的行为。如果capacity足够大,它可能会起作用,因为您从不查看大小。即使这样,v2的显示循环也无法正常工作。 -
@FrançoisAndrieux 不,他们都给出相同的 v2 = {4 5 6 1 2 3}
-
@FrançoisAndrieux 我的意思是 end()。
-
那么你有未定义的行为,只有 看起来 像它一样有效。如果您尝试添加更多元素,它最终会失败。并尝试复制
v2并查看它是否实际上 包含这些元素。 -
你也可以用
std::list试试这个,它几乎肯定不会看起来像它工作。它应该会更快地崩溃。
标签: c++