在 C++ 中,length()
函數(shù)的返回值通常表示字符串或容器(如 std::vector
, std::array
等)中元素的數(shù)量。具體來說:
對(duì)于字符串(std::string
)對(duì)象,length()
函數(shù)返回一個(gè)無符號(hào)整數(shù)(size_t
),表示字符串中字符的個(gè)數(shù)。
示例:
#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;
}
對(duì)于容器對(duì)象(如 std::vector
, std::array
等),length()
函數(shù)返回一個(gè)無符號(hào)整數(shù),表示容器中元素的個(gè)數(shù)。需要注意的是,這里的長(zhǎng)度是指容器中有效元素的個(gè)數(shù),不包括空元素(如 std::vector
中的默認(rèn)值)。
示例:
#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;
}