算法不改变它所操纵的容器的大小,为什么使用back_inserter也没有突破这个限制?

PS . C++ Primer 11.8

问:前面说过,算法不改变它所操纵的容器的大小,为什么使用back_inserter也没有突破这个限制?

例如:

vector<int> vec;
fill_n(vec.begin(),10,0);

其结果是未定义的,可能会导致运行时错误


vector<int> vec;
fill_n(back_inserter(vec),10,0)

却会向vector末尾添加10个元素,每个都是0;



答:

back_inserter 定义如下:

Defined in header <iterator>
  
template<class Container >
std::back_insert_iterator<Container> back_inserter( Container& c );
  
   

back_inserter is a convenience function template that constructs astd::back_insert_iterator for the containerc with the type deduced from the type of the argument.

back_inserter 会构造back_insert_iterator 类型的迭代器


template<class Container >

class back_insert_iterator :public std::iterator<std::output_iterator_tag,

                                                    void, void, void, void >
 (until C++17)
template<class Container >
class back_insert_iterator;
 (since C++17)
   

std::back_insert_iterator is an OutputIterator that appends to a container for which it was constructed. The container'spush_back() member function is called whenever the iterator (whether dereferenced or not) is assigned to. Incrementing thestd::back_insert_iterator is a no-op.

back_insert_iterator 会调用容器的push_back() 操作来添加元素


综上.fill_n 算法本身没有改变容器的大小, 是非常特殊的迭代器(back_insert_iterator) 调用了容器的操作push_back()改变了容器的大小


====================================================================================================

补充回答的一个类似的问题:

为什么算法不改变容器的大小?

答:算法基于迭代器来操作以实现泛型,而当需要在容器中添加或删除元素时, 不知道容器和容器元素的具体类型,就不可能知道需要增加或减少多少空间,就无法实现容器添加或删除元素的目的。 添加或删除容器元素的操作是与类型强相关的,而泛型的算法做不到这点


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值