简体   繁体   中英

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. That C++ standard library function does something clever to obviate the normal pointer decay you observe with C-style arrays.

C-array doesn't have methods.

Since C++17, you might use std::size :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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