从一个迭代器的开头复制到另一个迭代器的末尾迭代器

时间:2017-11-22 14:54:34

标签: c++ arrays iterator

这个令人费解的代码是在我的应用程序中找到的,我在第一个参数中用一个数组的迭代器编写了一个std :: copy,然后错误地将另一个数组的结束迭代器用于第二个参数。在查看这段代码时,我会想到要么什么也不会发生,否则代码会完全爆炸。然而,这段代码已经正常工作了几个月,总是产生相同的结果。

#include <array>
#include <stdio.h>

using std::array;
using std::printf;

int main()
{
    array<int,5> a = {0,1,2,3,4};
    array<int,5> b = {5,6,7,8,9};

    array<int,5> c;
    std::fill(c.begin(), c.end(), 0);

    std::copy(b.begin(), a.end(), c.begin());
    for(int element : c)
        printf("%d", element);
}

如果运行此代码here,您将看到输出为56789,即数组b的内容。我想知道为什么会这样。

0 个答案:

没有答案