c++中std::size是什么类型
作者:野牛程序员:2023-06-26 08:59:01 C++阅读 2830
在C++中,std::size
并不是一个类型,而是一个函数模板。它用于获取数组或容器的大小(元素数量)。std::size
可以用于各种类型的数组(包括原生数组和标准库容器),以及C++17之后的标准库容器。
std::size
函数模板定义如下:
template <class T, std::size_t N> constexpr std::size_t size(const T (&)[N]) noexcept;
该函数模板接受一个数组参数,并返回该数组的大小作为 std::size_t
类型的值。std::size_t
是一种无符号整数类型,用于表示内存中对象的大小。
以下是使用 std::size
的示例:
#include <iostream> #include <array> #include <vector> int main() { int arr[] = {1, 2, 3, 4, 5}; std::cout << "Array size: " << std::size(arr) << std::endl; std::array<int, 5> arr2 = {6, 7, 8, 9, 10}; std::cout << "std::array size: " << std::size(arr2) << std::endl; std::vector<int> vec = {11, 12, 13, 14, 15}; std::cout << "std::vector size: " << std::size(vec) << std::endl; return 0; }
输出:
Array size: 5 std::array size: 5 std::vector size: 5
注意,为了使用 std::size
函数模板,需要包含 <cstddef>
头文件。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
