一、array容器介绍
array 容器是 C++ 11 标准中新增的序列容器,通俗的说,它就是在 C++ 普通数组的基础上,增加了一些成员函数和全局函数。在使用上,它比普通数组更安全,且效率并没有因此变差。
二、array容器的使用
1.初始化
#include<iostream>
#include<array>
using namespace std;
int main()
{
int j=0;
array <int,5> tmp1={1,2,3,4,5};//一维数组初试化
array < array <int,2>,3> tmp2={1,2,3,4,5,6};//二维数组初始化
cout << "1维数组元素有: ";
for ( int i=0; i<5; i++)
cout << tmp1.at(i) << " ";
cout << endl;
cout << "2维数组元素有: ";
for ( int i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
cout << tmp2[i][j] << " ";
}
}
cout << endl;
return 0;
}
2.array容器成员函数demon
#include<iostream>
#include<array>
using namespace std;
int main()
{
int j=0;
array <int,5> tmp={6,7,8,9,10};
array <int,5> tmp1={1,2,3,4,5};
array < array <int,2>,3> tmp2={1,2,3,4,5,6};
cout << "1维数组元素有: ";
for ( int i=0; i<5; i++)
cout << tmp1.at(i) << " ";//at()用于访问数组的元素
cout << endl;
cout << "2维数组元素有: ";
for ( int i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
cout << tmp2[i][j] << " ";
}
}
cout << endl;
cout <<"获取第3个元素:"<<get<3>(tmp1)<<endl;
cout <<"数组第一个元素:"<<tmp1.front() << endl;//front()返回数组第一个元素
cout <<"数组最后一个元素:"<<tmp1.back() << endl;//back()返回数组最后一个元素
cout <<"数组容器的大小:"<<tmp1.size() << endl;//size() 返回数组容器的大小
cout <<"数组容器最大的大小:"<<tmp1.max_size() << endl;//max_size():返回数组容器可以包含的最大元素的个数,该值和size()返回的值是相同的
tmp1.swap(tmp); //swap() : The swap()和另一个数组元素进行交换
cout <<"交换后的数组:";
for ( int i=0; i<5; i++)
cout << tmp1.at(i) << " ";//at()用于访问数组的元素
cout << endl;
tmp1.empty()? cout << "tmp1 empty":
cout << "tmp1 not empty";
cout << endl;//empty() :array为空时,返回true,否则返回false
tmp1.fill(0);//fill()使用特定的值填充数组
cout <<"填充0后的数组:";
for ( int i=0; i<5; i++)
cout << tmp1.at(i) << " ";//at()用于访问数组的元素
cout << endl;
return 0;
}
运行结果: