溫馨提示×

c++ length函數返回值的含義是什么

c++
小樊
133
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女