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, | (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()改变了容器的大小
====================================================================================================
补充回答的一个类似的问题:
答:算法基于迭代器来操作以实现泛型,而当需要在容器中添加或删除元素时, 不知道容器和容器元素的具体类型,就不可能知道需要增加或减少多少空间,就无法实现容器添加或删除元素的目的。 添加或删除容器元素的操作是与类型强相关的,而泛型的算法做不到这点