我看到过使用
std::back_inserter
的 std::copy()
,但我使用了 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çois Andrieuxv2
并查看它是否实际上包含这些元素。 - François Andrieuxstd::list
来实现,但它几乎肯定看起来不像是有效的。它应该会更快地崩溃。 - François Andrieux