Problem

Hi guys . How do i measure the length of an array ? Better to say : how do i pass every element from array? i found with begin() , end(), etc but doesnt work. Please help.
Last edited on
closed account (48T7M4Gy)
int a[15]{};
size_t length = sizeof(a)/sizeof(int); // <---
sizeof(a)/sizeof(a[0]);
C++17: use std::size() http://en.cppreference.com/w/cpp/iterator/size

Pre-C++17: write a home grown version:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

namespace util
{
    template < typename T, size_t N >
    constexpr size_t size( const T (&)[N] ) noexcept { return N ; }
}

int main()
{
    double a[34] {} ;
    int b[67] {} ;
    std::cout << util::size(a) << ' ' << util::size(b) << '\n' ; // 34 67
}

http://coliru.stacked-crooked.com/a/e01eee2ba054df3a

Ideally, avoid constructs like sizeof(a)/sizeof(a[0]);.
This will give absurd results if an inadvertent array-to-pointer decay has taken place.


> begin() , end(), etc but doesnt work.

std::begin() and std::end() does work.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iterator>

int main()
{
    double a[34] {} ;
    int b[67] {} ;
    std::cout << std::end(a) - std::begin(a) << '\n' // 34
              << std::end(b) - std::begin(b) << '\n' ; // 67
}

http://coliru.stacked-crooked.com/a/d53f818bd76577c6
closed account (48T7M4Gy)
This will give absurd results if an inadvertent array-to-pointer decay has taken place.


And for anybody else who is interested to know a bit more about array-to-pointer decay ...
https://stackoverflow.com/questions/1461432/what-is-array-decaying
what I have always pondered about this question is not how to do it but why you don't know the size of the array ... which had to be available at compile time. If you need the size, pass it around or use a vector or bundle up a struct with size attached or something. You are trying to compute (with a slightly risky approach) .. a known compile time constant.

You can even cheat and put the size in the first location of the array (pascal style), either as data (POD types) or as raw bytes dumped in (a little kludgy for class types, and a dubious approach, but its been done).
Last edited on
Topic archived. No new replies allowed.