STL容器的resize方法

刚才写DFS程序,为了加个创建DFS树然后再次遍历的功能,把初始化的代码给封装到init()函数里,然后直接调用之后对同样是邻接表表示的DFS树进行DFS。

然后令人诧异的是竟然没有打印结果,调试发现我定义的deque<bool> visited;并没有被重置为false。

我在init()函数中的代码是

visited.resize(V, false);  // V是点数

然后我改成这样就没问题了

visited.resize(V);
for (bool& b : visited)
    b = false;

直接用YCM插件跳转到实现位置(毕竟STL源码是直接在系统里的不需要像glibc一样下载源码)

void
resize(size_type __new_size, const value_type& __x)
{
	const size_type __len = size();
	if (__new_size > __len)
		insert(this->_M_impl._M_finish, __new_size - __len, __x);
	else if (__new_size < __len)
		_M_erase_at_end(this->_M_impl._M_start
			+ difference_type(__new_size));
}              

新的size和原来的size相同的时候不作任何处理,而新的size大于原来的size时也只不过是在后面插入x,前面的元素不变。

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized

官方文档上也说得很清楚。

总结下来对自己用得少的接口,不要想当然地去猜它的功能,最好去确认一下。前些时候也想当然以为sscanf和fscanf一样,结果后者保存了文件指针的位置,而前者再次对同一字符串调用时会从头开始读。(其实很显然嘛,不然难道要sscanf要给每个字符串都保存个当前读取的指针位置?)

原文地址:https://www.cnblogs.com/Harley-Quinn/p/6654336.html