具有四个迭代器的类似复制的算法
copy-like algorithm with four iterators
是否有类似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;
}
}
不幸的是,没有这样的事情。最接近的是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&) { }
这与您的解决方案具有大致相同的性能,但更广泛地使用。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 错误:在"模板"之前预期主表达式,具有算法的复制功能
- 使用 while 循环和搜索算法进行复制
- STL算法函数,如累加,如果传递给它们的函数接受引用,请避免复制
- 是否有标准算法要复制直到
- 具有四个迭代器的类似复制的算法
- 是否允许标准库算法复制谓词参数
- 使用复制算法在 C++ 中打印矢量的格式问题
- 使用ifstream复制算法
- 生成和复制矢量的STL算法
- 为什么序列运算算法谓词是通过复制传递的
- 使用back_inserter复制算法
- 使用c++标准库,复制算法
- 另一个复制算法
- c++复制直到算法
- 我可以使用复制算法复制'set'中的'vector'元素吗?
- 作用于可移动但不可复制对象序列的变化STL算法的行为