概述
c++的容器类型大体可以分为顺序容器和关联容器两大类。
顺序容器 |
| ||||||
关联容器 |
|
成员函数介绍
本节先介绍array容器,作为c++11刚引入的容器类型。其成员可以分为指向头尾的*begin(),*end(),以及对数据修改的max_size(),front()等等。具体差别如下。
begin()/end() | begin()返回值指向数组的首元素,end()返回值指向尾元素的下一个地址。 |
cbegin()/cend() | |
rbegin()/rend() | rbegin()=end();rend()=begin。可以这样简单的理解。 |
crbegin()/crend() |
max_size() | 返回数组的最大长度 |
size() | 返回数组当前长度 |
empty() | 数组无元素返回真,否则为假。 |
front()/back() | front()返回数组首元素;back()返回数组尾元素。 |
data() | 返回数组第一个元素的指针 |
fill() | 把数组所以元素都置为指定值 |
swap() | 交换两个数组的值 |
打印方式
先说一点吧,array容器声明的时候,必须指定容器大小。如果不想指定容器大小,可以选择vector容器。下面介绍array数组的6种打印方式。
// array::begin example
#include <iostream>
#include <array>
using namespace std;
int main ()
{
array<int,5> myarray = { 2, 16, 77, 34, 50 };
cout << "1.use operator [] .myarray contains:";//打印1.use operator [] .myarray contains: 2 16 77 34 50
for ( int i=0;i< 5;i++)
cout << ' ' << myarray[i];
cout << '\n';
cout << "2.use function at.myarray contains:";//打印2.use function at.myarray contains: 2 16 77 34 50
for ( int i=0;i< 5;i++)
cout << ' ' << myarray.at(i);
cout << '\n';
cout << "3.use funciton begin/end.myarray contains:"; //打印3.use funciton begin/end.myarray contains: 2 16 77 34 50
for ( auto it = myarray.begin(); it != myarray.end(); ++it )
cout << ' ' << *it;
cout << '\n';
cout << "4.use funciton cbegin/cend.myarray contains:";//打印4.use funciton cbegin/cend.myarray contains: 2 16 77 34 50
for ( auto it = myarray.cbegin(); it != myarray.cend(); ++it )
cout << ' ' << *it;
cout << '\n';
cout << "5.use funciton rbegin/rend.myarray contains:";//打印5.use funciton rbegin/rend.myarray contains: 50 34 77 16 2
for ( auto it = myarray.rbegin(); it != myarray.rend(); ++it )
cout << ' ' << *it;
cout << '\n';
cout << "6.use funciton crbegin/crend.myarray contains:";//打印6.use funciton crbegin/crend.myarray contains: 50 34 77 16 2
for ( auto it = myarray.crbegin(); it != myarray.crend(); ++it )
cout << ' ' << *it;
cout << '\n';
return 0;
}
参考
1.介绍c++的在线网站 http://www.cplusplus.com/reference/array/array/array/
2.《c++ primer》第九章,十一章