Element count of an array in C++

前端 未结 11 1749
[愿得一人]
[愿得一人] 2020-12-05 10:38

Let\'s say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

I can

11条回答
  •  长情又很酷
    2020-12-05 10:42

    Since C++17 you can also use the standardized free function: std::size(container) which will return the amount of elements in that container.

    example:

    std::vector vec = { 1, 2, 3, 4, 8 };
    std::cout << std::size(vec) << "\n\n";    // 5
    
    int A[] = {40,10,20};
    std::cout << std::size(A) << '\n';      // 3
    

提交回复
热议问题