0
array<int, 5> b = {12,45,12,4};
int B[5] = { 12, 45, 12, 4 };
for (auto item : b)
{
    cout << item << endl;  // 12,45,12,4, 0
}
cout << endl;
for (auto item : B)
{
    cout << item << endl;  // 12,45,12,4, 0
}

What is the difference between array<int,5> b; and int b[5];?

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
NewB
  • 314
  • 3
  • 11

1 Answers1

3

Template class std:;array is defined as a structure. It is an aggregate and has some methods as for example size(). The difference is for example that arrays have no assignment operator. You may not write

int b[5] = { 12, 45, 12, 4 };
int a[5];

a = b;

while structures have an implicitly defined assignment operator.

std::array<int, 5> b = { 12, 45, 12, 4 };
std::array<int, 5> a;

a = b;

Also using arrays you may not use initialization lists to assign an array. For example the compiler will issue an error for the following statement

int b[5];
b = { 12, 45, 12, 4, 0 };

However you can do these manipulations with std::array For example

std::array<int, 5> b;
b = { 12, 45, 12, 4, 0 };
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303