序列式容器————array

目录

介绍

1 构造函数

2 fill()

3 元素的获取

4 size()

5 empty()

6 front()

7 back()

8 get<n>

9 迭代器(待补充)

10 元素的比较

 

介绍

array<T,N> (数组容器) :是一个长度固定的序列,有 N 个 T 类型的对象,不能增加或删除元素

和标准数组相比,array 容器的额外幵销很小,但提供了两个优点:如果使用 at(),当用一个非法的索引访问数组元素时,能够被检测到,因为容器知道它有多少个元素,这也就意味着数组容器可以作为参数传给函数,而不再需要单独去指定数组元素的个数。

使用 array 容器类型时,需要在源文件中包含头文件 array。


 

1 构造

array<double,100> data;//创建能存100个元素的空数组
array<double,100> data{};//创建能存100个元素的数组,并初始化全为0

 

2 fill()

将所有元素设定为定值。

data.fill(3.1415)

 

3 元素的获取

values[4] = values[3] + 2.O*values[1];

values.at (4) = values.at(3) + 2.O*values.at(1);

一旦获得一个越界的索引值,at函数会抛出异常,而[]不会。

 

4 size()

返回包含的元素的个数。

 

5 empty()

判断是否为空

 

6 front()

返回数组第一个元素

 

7 back()

返回数组最后一个元素

 

8 get<n>

获得数组第n个元素。

std::get<3>(words);//输出words数组第3个元素

 

9 迭代器

 

10 元素的比较

容器被逐元素地比较。
std::array<double,4> these {1.0, 2.0, 3.0, 4.0}; std::array<double,4> those {1.0, 2.0, 3.0, 4.0}; std::array<double,4> them {1.0, 3.0, 3.0, 2.0}; if (these == those) std::cout << "these and those are equal." << std::endl; if (those != them) std::cout << "those and them are not equal."<< std::endl; if (those < them) std::cout << "those are less than them."<< std::endl; if (them > those) std::cout << "them are greater than those." << std::endl;

只要它们存放的是相同类型、相同个数的元素,就可以将一个数组容器赋给另一个。例如:

them = those;

 

posted @ 2019-09-01 11:06  Austin_anheqiao  阅读(206)  评论(0编辑  收藏  举报