gpt4 book ai didi

c++ - 为什么在 std::copy 期间使用 std::back_inserter 而不是 end()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:43 26 4
gpt4 key购买 nike

我见过 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;
}

最佳答案

第一个将值插入到 vector 中,另一个是未定义的行为,它将项目写入刚好超过 vector 末尾的位置。

尝试打印生成的 vector :

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

(在 Debug模式下引发断言失败)

它在您的特定编译器 中为您工作的事实并不能说明它是正确的。貌似上类是UB的典型表现。

关于c++ - 为什么在 std::copy 期间使用 std::back_inserter 而不是 end()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54297642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com