[英]How to give a variable the size of array using size() function in c++?
When I write the code it shows error当我写代码时它显示错误
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = {12, 3, 4, 15};
int n = arr.size();
cout << "Size of array is " << n;
return 0;
}
Compilation failed due to following error(s).
main.cpp:7:17: error: request for member ‘size’ in ‘arr’, which is of non-class type ‘int [4]’
7 | int n = arr.size();
| ^~~~
it also didn't work for vector array i tried that also can't understand the problem它也不适用于矢量数组我试过也无法理解问题
As a rule of thumb, use根据经验,使用
std::vector<int> arr = {12, 3, 4, 15};
with和
arr.size();
returning the number of elements, unless you have a good reason not to.返回元素的数量,除非你有充分的理由不这样做。
Failing that, std::size(arr)
will give you the number of elements, but only if arr
has not already decayed to a pointer type by virtue of your receiving it as a function parameter.如果做不到这一点,
std::size(arr)
将为您提供元素的数量,但前提是arr
还没有因为您将其作为 function 参数接收而衰减为指针类型。 That C++ standard library function does something clever to obviate the normal pointer decay you observe with C-style arrays. C++ 标准库 function 巧妙地避免了您在 C 风格 arrays 中观察到的正常指针衰减。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.