首先说明,在C++ string类中,size() 和length()方法是没有任何区别的。
我们可以看 Microsoft Visual Studio 10.0\VC\include\xstring 文件,转到此两个方法的定义
size_type length() const
{ // return length of sequence
return (this->_Mysize);
}
size_type size() const
{ // return length of sequence
return (this->_Mysize);
}
length是因为沿用C语言的习惯而保留下来的,string类最初只有length,引入STL之后,为了兼容又加入了size,它是作为STL容器的属性存在的,便于符合STL的接口规则,以便用于STL的算法。