我今天遇到了这个问题,我认为我应该将其发布以供社区引用和/或意见。
标准 C++ 容器 vector 、双端队列、列表和字符串提供 assign
成员函数。有两个版本;我主要对接受迭代器范围的那个感兴趣。 Josuttis book它的描述有点含糊。从页。 237...
Assigns all elements of the range [beg,end); this is, is replaces all existing elements with copies of the elements of [beg,end).
它没有说明如果受让人容器的大小与分配的范围不同会发生什么。它会被截断吗?会自动扩展吗?这是未定义的行为吗?
最佳答案
这是我发现的。事实证明我不必担心默默地做错事。标准再次给出了答案。来自第 23.2.6.1 节:
void assign(Iter first, Iter last);
Effects:
erase(begin(), end());
insert(begin(), first, last);
所以它实际上只是 clear()
的快捷方式,后跟整个范围的 insert
。
关于c++ - 容器的分配函数可能会溢出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2539081/