在 C++ 中,length()
函數的返回值通常表示字符串或容器(如 std::vector
, std::array
等)中元素的數量。具體來說:
對于字符串(std::string
)對象,length()
函數返回一個無符號整數(size_t
),表示字符串中字符的個數。
示例:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::cout << "The length of the string is: " << str.length() << std::endl; // 輸出:The length of the string is: 13
return 0;
}
對于容器對象(如 std::vector
, std::array
等),length()
函數返回一個無符號整數,表示容器中元素的個數。需要注意的是,這里的長度是指容器中有效元素的個數,不包括空元素(如 std::vector
中的默認值)。
示例:
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::cout << "The length of the vector is: " << vec.size() << std::endl; // 輸出:The length of the vector is: 5
return 0;
}