为什么在 std::copy 中使用 std::back_inserter 而不是 end()

Why use std::back_inserter instead of end() during std::copy?

本文关键字:std inserter end back copy 为什么      更新时间:2023-10-16

我见过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的典型表现。