straying(【小白必经之路:玩转STL】array容器)
导读:此篇随笔将示范array容器的基本操作...
此篇随笔将示范array容器的基本操作
1.介绍
array容器在C++普通数组的基础上 ,添加了一些函数 。在使用上 ,它比普通数组更安全 。
2.头文件及命名空间
3.举例
array<double,10> arr;//声明一个装有10个double型元素的数组容器 ,容器名为arr
4.初始化
1 //array容器不会像普通数组那样进行默认初始化
2 array<int,10> arr01 {};//全部初始化为0
3 array<int,10> arr02 {1,2,3};//前三个元素初始化为1,2,3, 其他元素初始化为0
//上述初始化可以加等号 ,但是务必注意必须显性初始化 ,异于普通数组的默认初始化
5.遍历
//法1 数组名[下标]
#include<iostream>
#include<array>
using namespace std;
int main(){
array<int,10> arr {1,3,5,7,9,2,4,6,8,10};
for (size_t i = 0; i < arr.size(); i++)
{
cout<<arr[i]<<;
}
return 0;
}
//法2 迭代器
#include<iostream>
#include<array>
using namespace std;
int main(){
array<int,10> arr {1,3,5,7,9,2,4,6,8,10};
// for (array<int,10>::iterator it = arr.begin(); it != arr.end(); it++)
// {
// cout<<*it<< ;
// }
for (auto it = arr.begin(); it != arr.end(); it++)
{
cout<<*it<<;
}
return 0;
}
6.快速求和:accumulate()函数
使用accumulate()函数实现数组快速求和
#include<iostream>
#include<array>
#include<numeric>//accumulate函数
using namespace std;
array<int,10> arr {1,3,5,7,9,2,4,6,8,10};
int main(){
cout<<accumulate(arr.begin(),arr.end(),0);//第三个参数相当于int sum = 0 的初始值0
return 0;
}
//输出:55
//若把第三个参数改为3 ,那么输出将会是58(55+3=58).
7.size()函数
//获取容器内元素的个数
#include<iostream>
#include<array>
using namespace std;
array<int,10> arr={1,3,5,7,9,2,4,6,8,10};
int main(){
cout<<"arr内元素个数为:"<<arr.size()<<endl;
return 0;
}
//输出:arr内元素个数为:10
8.empty()函数
//若容器为空则返回真
#include<iostream>
#include<array>
using namespace std;
array<int,0> arr;//第二个参数为0 ,容器为空
int main(){
if (arr.empty())
{
cout<<"arr is empty"<<endl;
}
return 0;
}
//输出:arr is empty
9.fill()函数
//给所有元素初始化为特定值
#include<iostream>
#include<array>
using namespace std;
array<int,5> arr;
int main(){
arr.fill(-1);
for (size_t i = 0; i < arr.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
//输出:-1 -1 -1 -1 -1
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集 、发布本站内容到任何网站 、书籍等各类媒体平台 。如若本站内容侵犯了原著者的合法权益 ,可联系我们进行处理 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!