简体   繁体   English

如何在 c++ 中使用 size() function 给变量数组的大小?

[英]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 中观察到的正常指针衰减。

C-array doesn't have methods. C 数组没有方法。

Since C++17, you might use std::size :从 C++17 开始,您可以使用std::size

const auto n = std::size(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM