在string中,length()和size()等价,都用来返回字符串的字符数量。
在vector等其他容器中,没有length()函数,一般使用size()返回容器中的元素数量。
示例代码:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string str = "Hello, World!";
cout << "Length: " << str.length() << endl; // 输出:Length: 13
cout << "Size: " << str.size() << endl; // 输出:Size: 13
vector<int> vec = {1, 2, 3, 4, 5};
cout << "Size: " << vec.size() << endl; // 输出:Size: 5
// cout << "Length: " << vec.length() << endl; // 错误:vector 没有 length() 方法
return 0;
}