c++

c++ length函数返回值的含义是什么

小樊
81
2024-09-24 21:15:11
栏目: 编程语言

在 C++ 中,length() 函数的返回值通常表示字符串或容器(如 std::vector, std::array 等)中元素的数量。具体来说:

  1. 对于字符串(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;
    }
    
  2. 对于容器对象(如 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;
    }
    

0
看了该问题的人还看了