C++ STL中判断list为空,size()==零和empty()有什么区别

C++ STL中判断list为空,size()==0和empty()有什么区别

关于两个的区别,首先size()==0为bool表达式,empty()为函数调用,这一点很明显。查看源代码

bool empty() const { return _M_node->_M_next == _M_node; }    
size_type size() const {    
  size_type __result = 0;    
  distance(begin(), end(), __result);    
  return __result;    
}  

 可以看出empty直接检查标记节点,而size是通过求首尾迭代器的距离来获取元素个数的。

 

查看的源代码来自http://www.sgi.com/tech/stl/download.html