array 容器是 C++ 11 标准中新增的序列容器,简单地理解,它就是在 C++ 普通数组的基础上,添加了一些成员函数和全局函数。
一、调用方法
#include <array>using namespace std;
二、代码中的使用
#include <iostream>#include <array>#include <string>using namespace std;int main(){array<int, 10> arr0{1, 2, 3}; //初始化前三个元素,剩余的元素初始化为0array<double, 5> arr1;//未初始化,随机值array<string, 19> arr2;int i = 0;/*访问元素*/for (i=0; i<arr0.size(); i++){cout<<arr0[i]<<endl; //无边界检查cout<<arr0.at(i)<<endl; //边界检查 越界值时,程序会抛出 std::out_of_range 异常cout<<get<0>(arr0)<<endl; //get<>()该模板函数中,参数的实参必须是一个在编译时可以确定的常量表达式,所以它不能是一个循环变量cout<<*(arr0.data()+i)<<endl;//data()方法返回第0个元素数据的地址,主要用于array的数据拷贝}/*判断是否存在元素*/if(arr0.empty()){cout<<"The container has no elements.\n";}else{std::cout << "The container has "<< arr0.size()<<"elements.\n";}/*迭代器*///begin()/end() 和 cbegin()/cend()auto first = arr0.begin(); //auto first = std::begin(values); 成员函数定义方式auto last = arr0.end(); //auto last = std::end (values); 成员函数定义方式i = 0;while(first != last){*first = i;first++;i++;}//cbegin cend和begin end用法相同,但因为是const类型,故只能访问元素,不能修改auto cfirst = arr0.cbegin();auto clast = arr0.cend();while (cfirst != clast){cout<<*cfirst<<" ";++cfirst;}//rbegin()/rend() 和 crbegin()/crend() -- 反向迭代器auto rfirst = arr0.rbegin();auto rlast = arr0.rend();i = 0;while (rfirst != rlast){*rfirst = i;++rfirst;i++;}return 0;}
