温馨提示×

c++ length函数与size函数有何区别

c++
小樊
81
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