【问题标题】:copy-like algorithm with four iterators具有四个迭代器的类复制算法
【发布时间】:2012-07-19 12:15:55
【问题描述】:

是否有类似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;
    }
}

【问题讨论】:

  • 你刚做了一个。你的问题是什么?
  • 也许你可以使用C++11的std::copy_if函数?
  • 可能是partial_sort_copy 的破解版?虽然坦率地说,我没有看到让它复杂化的意义......
  • 一个很好的资源是cppreference,如果你想找到替代品,看看那里。
  • @SergeyK 我的代码旨在成为规范,而不是交付质量,高度优化的实现。

标签: c++ algorithm stl iterator copy


【解决方案1】:

不,可悲的是没有这样的事情。最接近的是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&) { }

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

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2016-05-09
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2018-09-23
    相关资源
    最近更新 更多