std::array

std::array

std::array是在c++11中引入的,对原来C语言的数组的一个包装器,具有额外的优点。这是一种具有恒定大小元素的顺序容器。

其模版为:

1
2
template < class T, size_t N > 
class array;

T为元素类型,N为数组元素的个数。

头文件为:

1
#include <array>

Defining and Initializing an std::array<> object

举两个例子:

1
2
std::array<std::string, 200> arr1;
std::array<int, 10> arr3 = { 34, 45 };//Init: 34 , 45 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,

std::array还提供了一个方法可以一次性对所有的元素设置相同的值。

1
2
3
std::array<int, 10> arr4;
// Fill all elements in array with same value
arr4.fill(4);

How to get the size of std::array

1
arr.size();

How to access elements in std::array

  • operator []:访问超出范围的元素时会引起undefined behaviour;
1
int x = arr[2];
  • at():访问超出范围的元素时会抛出out_of_range异常;
1
int x = arr.at(2);
  • std::tuple’s get<>():访问超出范围的元素时会编译错误;
1
int x = std::get<2>(arr);

How to Iterate over a std::array<> object

对array的遍历,存在四种方法:

  • 使用基于范围的迭代循环;
  • 使用循环;
  • 使用迭代器;
  • 使用for_each;