6

是否有一个类似std::copy的算法接受四个迭代器,表示两个范围?

基本上,只要任一范围用完,它就应该停止复制:

template<typename Iter>
void copy_range(Iter begin1, Iter end1, Iter begin2, Iter end2)
{
    for (; (begin1 != end1) && (begin2 != end2); ++begin1, ++begin2)
    {
         *begin2 = *begin1;
    }
}
4

1 回答 1

10

不,可悲的是没有这样的事情。最接近的是std::copy_n.

当然还有你刚刚写的算法。

根据使用的迭代器类型(随机或非随机),使用它比您的算法更有效(因为每次迭代只需进行一次检查):

std::copy_n(begin1,
            std::min(std::distance(begin1, end1), std::distance(begin2, end2)),
            begin2);

另一种选择是检查输出迭代器,类似于此(粗略草图,未检查代码):

template<class Iter>
class CheckedOutputIter {
public:
    // exception used for breaking loops
    class Sentinel { }

    CheckedOutputIter()
        : begin(), end() { }

    CheckedOutputIter(Iter begin, Iter end)
        : begin(begin), end(end) { }

    CheckedOutputIter& operator++() {
        // increment pas end?
        if (begin == end) {
            throw Sentinel();
        }

        ++begin;
        return *this;
    }

    CheckedOutputIter operator++(int) {
        // increment past end?
        if (begin == end) {
            throw Sentinel();
        }

        CheckedOutputIter tmp(*this);

        ++begin;

        return tmp;
    }

    typename iterator_traits<Iter>::value_type operator*() {
        return *begin;
    }


private:
    Iter begin, end;
};

用法:

try {
    std::copy(begin1, end1, CheckedOutputIter(begin2, end2));
} catch(const CheckedOutputIter::Sentinel&) { }

这与您的解决方案具有大致相同的性能,但它的使用范围更广。

于 2012-07-19T12:20:11.647 回答