在 C++ 中,length()
和 size()
函數(shù)都用于獲取容器(如字符串、向量、列表等)中元素的數(shù)量。然而,它們分別屬于不同的庫,并且在某些情況下可能不可用。
length()
函數(shù):通常用于獲取字符串的長度。它是 C++ 標準庫 <cstring>
中定義的函數(shù),適用于 C 風格字符串(char*
)。使用示例:#include <cstring>
#include <iostream>
int main() {
char str[] = "Hello, World!";
std::cout << "Length of the string: " << std::strlen(str) << std::endl;
return 0;
}
size()
函數(shù):用于獲取容器中元素的數(shù)量。它是 C++ 標準庫 <vector>
、<string>
、<list>
等容器中定義的成員函數(shù)。使用示例:#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::string str = "Hello, World!";
std::cout << "Size of the vector: " << vec.size() << std::endl;
std::cout << "Size of the string: " << str.size() << std::endl;
return 0;
}
總結(jié):length()
函數(shù)用于獲取 C 風格字符串的長度,而 size()
函數(shù)用于獲取容器中元素的數(shù)量。在實際編程中,根據(jù)需要選擇合適的函數(shù)。