1

I realize that this is very basic but would someone mind explaining the difference between these two array declarations:

#include <array>
array<int, 5> myints;

...and:

int myints[5];

...and why myints.size() works with the first declaration but not the second.

Ravindra S
  • 6,302
  • 12
  • 70
  • 108
user3111174
  • 121
  • 1
  • 1
  • 5
  • 5
    Please get yourself [a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Dec 18 '13 at 13:46

4 Answers4

8
int myints[5];

This is an array of five integers.
It is a basic language structure in both C and C++.
There are no member functions on built-in types.

std::array<int, 5> myints;

This is an instance of the standard library class std::array<int, 5>
(itself an instance of the standard library class template std::array<T, N>).
It is a wrapper around the basic array, providing utility member functions (such as size()) for convenience.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

array is a class (standard stl container) that has methods and wraps many functions that you want to apply to more standard static arrays.

Take a look to std::vector also. See also http://www.cplusplus.com/reference/vector/vector/ for informations how to use arrays and vectors.

In particular vectors are more suited to dynamic memory allocation, while your int myints[5] declaration is called static allocation and has some big limitations in terms of memory that you can allocate.

linello
  • 8,451
  • 18
  • 63
  • 109
  • 2
    Nitpick: `std::array` is a *C++ standard library* container, not an stl container, and not a class. If you look at the [STL](http://www.sgi.com/tech/stl/table_of_contents.html), you will see it has no `array` container. – juanchopanza Dec 18 '13 at 13:49
1

int myints[5]; gives you an "array of 5 ints". This "array" type is a language feature. The object it gives you is basically 5 ints next to each other in memory. This array type is not a class type, so it doesn't have member functions.

std::array<int, N> myints; gives you an std::array object. std::array is a class type from the standard library and so may have member functions, such as the member function size. The class encapsulates a fixed size array and provides a nice interface.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

in first declaration array myints; here myins is a object of array class, which is a thin wrapper over c array. and this class has a function of size() that will return the size. and the second declaration is a c-style array. this is not a class or structure.

rajenpandit
  • 1,265
  • 1
  • 15
  • 21