2012-07-19 18 views
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; 
    } 
} 
+2

你刚刚做了一个。你的问题是什么? – 2012-07-19 12:20:11

+0

也许你可以使用C++ 11 ['std :: copy_if'](http://en.cppreference.com/w/cpp/algorithm/copy)函数? – 2012-07-19 12:21:52

+0

可能是'partial_sort_copy'的被黑客版本?虽然我坦率地没有看到它的复杂点... – Nim 2012-07-19 12:22:02

回答

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&) { } 

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

相关问题