了解 std::copy

Understanding std::copy

阅读此代码以教授如何构建简单的双精度向量后:

class vector
{
    int sz;
    double* elem;

public:
    vector(int s)
        :sz{s}, elem{new double[sz]}
    {
        for (int i = 0; i < sz; ++i)elem[i] = 0.0;
    }
    vector(initializer_list<double>lst)
        :sz{ int(lst.size()) }, elem{ new double[sz] }
    {
        copy(lst.begin(), lst.end(), elem);
    }
    vector(const vector&);
    ~vector(){ delete[] elem; }
    double get(int n) const { return elem[n]; }
    void set(int n, double v) { elem[n] = v; }
};

复制构造函数定义为:

vector::vector(const vector& arg)
    :sz{ arg.sz }, elem{new double[arg.sz]}
{
    copy(arg.elem, arg.elem + sz, elem);
}

范围 arg.elem, arg.elem + sz 实际上不应该是

arg.elem, arg.elem + sz - 1

?

std::copy 实现如下:

template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last, 
              OutputIt d_first)
{
    while (first != last) {
        *d_first++ = *first++;
    }
    return d_first;
}

last指向的元素未被复制。如果是则以下代码:

std::vector<int> in;
std::vector<int> out;
std::copy(in.begin(), in.end(), std::back_inserter(out.begin()))

不行。你必须做这样的事情,这在空向量的情况下不起作用:

std::vector<int> in;
std::vector<int> out;
std::copy(in.begin(), in.end() - 1, std::back_inserter(out.begin()))

在 C++ 中,各种函数接受开始迭代器或指针,以及结束迭代器或指针。起始迭代器包含在任何操作中,无论是复制还是排序等等,但不包括结束迭代器或指针。通常操作是start iterator to (end iterator - 1)。来自 std::copy 的文档:

Input iterators to the initial and final positions in a sequence to be copied. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.

这就是为什么在容器中 end() 迭代器不指向最后一个元素的原因。例如,std::vector::end() 是指向最后一个成员的迭代器。