<STL系列>array

来源:互联网 发布:凡高网络 编辑:程序博客网 时间:2024/06/14 09:17

c++中<array>跟c++中的vector一样,很好用,但效率比vector高。

由于<array>是c++11中新添加的STL,因此编译命令为(myarray.cpp):g++   myarray.cpp  -std=c++11

功能如下:

at :指定数组中的位置

back :返回数组中最后一个元素值

begin :返回指向第一个元素的迭代器,用itetator迭代器

cbegin :返回指向第一个元素的迭代器,用const_iterator迭代器

cend :返回指向最后元素的下一位迭代器

crbegin :返回指向逆序数组的第一个元素的迭代器,用const_iterator迭代器

crend :返回指向逆序数组最后元素的下一位迭代器

data :返回数组首地址

empty :判断数组是否为空,为空返回true

end :返回指向最后一个元素的迭代器

fill :初始化数组元素为同一个值

front :返回数组的第一个元素值

max_size :返回数组最大元素个数

opetator[] :使用下标访问数组

rbegin :返回指向逆序数组的第一个元素的迭代器,用iterator迭代器

rend :返回指向逆序数组最后元素的下一位迭代器

size :返回数组的元素的实际个数

swap :数组交换

以下程序是在机器上编译测试通过的

示例一如下:

#include <iostream>#include <array>using namespace std;int main(int argc, char **argv){//定义含有10个int类型的数组array<int,10> myarr;//将数组初始化为0myarr.fill(0);//将数组数据更新为对应的0-9for (int i = 0; i < myarr.size(); i ++) {myarr[i] = i;}//正序遍历数组for (array<int,10>::iterator ite = myarr.begin(); ite != myarr.end(); ite ++) {cout << *ite << ' ';}cout << endl;//正序遍历数组for (auto ite = myarr.begin(); ite != myarr.end(); ite ++) {cout << *ite << " ";}cout << '\n';//逆序遍历数组for (auto ite = myarr.rbegin(); ite != myarr.rend(); ite ++) {cout << *ite << " ";}cout << "\n";//逆序遍历数组for (array<int,10>::const_iterator ite = myarr.crbegin(); ite != myarr.crend(); ite ++) {cout << *ite << " ";}cout << endl;}
输出结果如下:

0  1  2  3  4  5  6  7  8  9

0  1  2  3  4  5  6  7  8  9

9  8  7  6  5  4  3  2  1  0

9  8  7  6  5  4  3  2  1  0
示例二如下:

#include <iostream>#include <array>using namespace std;int main(int argc,char **argv){//定义数组并手动初始化array<int,5> myarr2,myarr1 = {100,200,300,400,500};//获得数组元素实际个数cout << "myarr1 size:" << myarr1.size() << endl;//获得数组可容纳的最大元素个数cout << "myarr1 max_size:" << myarr1.max_size() << endl;//获得第一个元素值cout << "myarr1 front:" << myarr1.front() << endl;//获得最后一个元素值cout << "myarr1 back:" << myarr1.back() << endl;//判断myarr2是否为空,若是执行赋值操作if (myarr2.empty) {for (int i = 0; i < myarr2.size(); i ++) {myarr2.at(i) = i + 1;}}//数组进行交换swap(myarr1,myarr2);//交换后的结果for (auto ite = myarr1.begin(); ite != myarr1.end(); ite ++) {cout << *ite << " ";}cout << endl;for (auto ite = myarr2.begin(); ite != myarr2.end(); ite ++) {cout << *ite << " ";}cout << endl;}
输出结果如下:

myarr1 size:5

myarr1 max_size:5

myarr1 front:100

myarr1 back:500

1  2  3  4  5

100  200  300 400 500







0 0
原创粉丝点击