public
Last active

Simple functions for better usage of arrays

  • Download Gist
arrays.h
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
// begin() and end() functions for arrays (C++03)
//
// Written in 2012 by Martinho Fernandes
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// Installation:
// Place this into a header file and #include it in your code. Done.
//
// Usage:
// int array[10]; // create an array of ten ints
// int* first = so::begin(array); // get a pointer to the beginning
// int* last = so::end(array); // get a pointer to one past the end
// size_t n = so::size(array); // get the size of the array (10)
#ifndef SO_BEGIN_END_HPP_INCLUDED
#define SO_BEGIN_END_HPP_INCLUDED
 
#include <cstddef> // size_t
 
namespace so {
template <typename T, std::size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
 
template <typename T, std::size_t N>
T* end(T(&arr)[N]) { return &arr[0] + N; }
 
template <typename T, std::size_t N>
std::size_t size(T const(&)[N]) { return N; }
}
 
#endif

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.