加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么std :: fill使用ForwardIterator而不是OutputIterato

发布时间:2020-12-16 10:06:07 所属栏目:百科 来源:网络整理
导读:(这个问题与 Why does std::max_element require a ForwardIterator?具有相同的“问题模板”,但答案必须不同,因为std :: fill不会将迭代器返回到输出序列中.) std::fill 定义为仅在输出范围由一对ForwardIterators给出时才起作用.但是,表面上类似的 std::fil
(这个问题与 Why does std::max_element require a ForwardIterator?具有相同的“问题模板”,但答案必须不同,因为std :: fill不会将迭代器返回到输出序列中.)

std::fill定义为仅在输出范围由一对ForwardIterators给出时才起作用.但是,表面上类似的std::fill_n与OutputIterator一起工作正常.

当然算法很简单

template<class OutIt,class T>
void fill(OutIt first,OutIt last,T value)
{
    while (first != last) {
        *first = value;
        ++first;
    }
}

这个算法怎么样需要ForwardIterator?我错过了什么?

解决方法

输出迭代器无法比较. ==和!=运算符未定义输出迭代器.

你需要一个前向迭代器,因为它

satisfies the requirements of an input iterator

它支持EqualityComparable.

对于输出迭代器,std :: fill不能先与last进行比较:

while (first != last) {

不支持,用于输出迭代器.

std :: fill_n避免了这种比较,它只是使用计数器写入迭代器,所以它只需要一个输出迭代器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读