溫馨提示×

c++ length函數與size函數有何區別

c++
小樊
253
2024-09-24 21:17:09
欄目: 編程語言

在 C++ 中,length()size() 函數都用于獲取容器(如字符串、向量、列表等)中元素的數量。然而,它們分別屬于不同的庫,并且在某些情況下可能不可用。

  1. length() 函數:通常用于獲取字符串的長度。它是 C++ 標準庫 <cstring> 中定義的函數,適用于 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;
}
  1. size() 函數:用于獲取容器中元素的數量。它是 C++ 標準庫 <vector>、<string>、<list> 等容器中定義的成員函數。使用示例:
#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;
}

總結:length() 函數用于獲取 C 風格字符串的長度,而 size() 函數用于獲取容器中元素的數量。在實際編程中,根據需要選擇合適的函數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女