STL之数组
1.定义形式:
array <int, 5> d1={2, 1, 3, 4, 1};
array <float, 5> d2={1.1,2.1,2.2,3.1,4.1};
array<string,5> d3={“one”,“tow”,“three”,“four”,"five’;}
2.常见方法
2.1 swap();
swap(d1,d2);
实例:
//数组加起来的容器
int total={0};
//数组交换函数
swap(d1, d2);
cout << “d1的数组内容是:”;
// array.at()方法可以检查数组越界;
for (int i = 0; i < d1.size(); i++)
{
cout << d1.at(i) << " ";
}
for (int i = 0; i < d1.size(); i++)
{
total+=d1[i];
}
cout<<endl<<"total is "<<total;
2.2 fill(); 填充函数
将数组全部置换成一个数;
//填充函数
d2.fill(2);
cout << endl<< “data1的数组内容是:”;
for (int i = 0; i < d2.size(); i++)
{
cout << d2.at(i) << " “;
}
2.3 判断是否为空的函数
if(d1.empty())
cout<<endl<<“the array is not elements”;
else{
cout<<endl<<“the size of arry are :”<<d1.size();
}
2.4 获取元素模板
get(array)方法更加安全
//---->提供了一种不需要在运行时检查,但能用安全的索引值访问元素的方式
array <int, 5> d3={2, 1, 3, 4, 1};
cout<<d3[3]<<endl;
cout<<get<3>(d3)<<endl;
string d33=get<4>(d3);
cout<<d33<<endl;
3.for循环简洁写法
for(auto &i: a3){
cout<<i<<” “;
}
cout<<endl;
for(auto &k: d1){
cout<<k<<” ";
}
cout<<endl;