C++ STL array

(一)了解array
array是一个静态数组的容器,固定长度,但是也有迭代器,特别是at方法可以检测越界,同时,array的使用也比较方便。
不过,为觉得不如使用普通的数组。。。

(二)Test_Demo

#include <iostream>
#include <array>
#include <algorithm>

using namespace std;

int main()
{
	array<char, 10> a_char;
	array<int, 10> a_int{1, 3, 2};
	array<int, 10> a_clone = a_int;

	//迭代器遍历:会遍历整个array大小
	for (auto it : a_int)
		cout << it << " ";
	cout << endl;

	for (auto it = a_int.begin(); it != a_int.end(); ++it)
		cout << *it << " ";
	cout << endl;

	for (size_t i = 0; i < a_int.size(); ++i)//a_int.size() = 10
		cout << a_int.at(i) << " ";	//at方法会做越界检测,这也是array的一大特点
	cout << endl;

	//fill
	a_int.fill(2);//output:2 2 2 2 2 2 2 2 2 2  fill用一个value填满array,会覆盖原有
	for (auto it = a_int.begin(); it != a_int.end(); ++it)
		cout << *it << " ";
	cout << endl;

	//返回array的起始指针
	int *ptr = a_int.data();
	for (size_t i = 0; i < a_int.size(); ++i) {
		cout << *(ptr + i) << " ";  //注意不要越界
	}
	cout << endl;

	//头尾
	int back = a_clone.back();//整个array的尾部数据
	int front = a_clone.front();
	cout << "front = " << front << "back = " << back << endl;

	//swap
	cout << "old data:(a_int, a_clone)" << endl;
	for (auto it = a_int.begin(); it != a_int.end(); ++it)
		cout << *it << " ";
	cout << endl;
	for (auto it = a_clone.begin(); it != a_clone.end(); ++it)
		cout << *it << " ";
	cout << endl;
	a_clone.swap(a_int);//swap 要保证两个array的类型和大小相同
	cout << "new data:(a_int, a_clone)" << endl;
	for (auto it = a_int.begin(); it != a_int.end(); ++it)
		cout << *it << " ";
	cout << endl;
	for (auto it = a_clone.begin(); it != a_clone.end(); ++it)
		cout << *it << " ";
	cout << endl;
	
	//排序
	cout << "sort";
	sort(a_int.begin(), a_int.end());//这样会对整个array排序(升序),需要灵活调节区间
	for (auto it = a_int.begin(); it != a_int.end(); ++it)
		cout << *it << " ";
	cout << endl;
	//array中与成员函数无关的鸡肋函数
	//tuple_size;  tuple_element;   get<1>(a_int); 

	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值