首页 > 解决方案 > 为什么在 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; 
}

标签: c++

解决方案


第一个将值插入向量中,另一个是未定义的行为,它将项目写入向量末尾的位置。

尝试打印结果向量:

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


推荐阅读