C++ STL容器概述

C++ STL容器概述(1)

摘要:

C++标准库为我们提供了很多的容器类型,它们有一个共同的特点就是,泛型。可以说C++标准库与泛型编程有着紧密的联系。那么接下来的几篇博客我会带大家看一些常见C++容器类型,并且简单的阐述一下其底层原理,希望能够帮助大家在以后的编程中能够更好的去选择的和使用容器。

array容器类型:

提到array,我想大家应该都不陌生,没错,就是数组。在C++标准库中,array被封装为一个新的数据类型。这个新的数据类型能够让我们更好的使用数组。下面我们用一张图片来表述一下array的特性。
在这里插入图片描述
C++ STL中的array与我们平时使用的数组没什么两样,只不过是STL对他进行了一个更人性化的封装。我们可以看到,array类型是不可扩展的,我们必须在创建对象时声明它的大小,而且一般情况下,他的大小也是不可更改的。跟我使用的array的方式相同,同样呢array也支持我们去根据索引下标取值,当然也可以使用array提供我们的函数array.at()去取值。下面我们通过一串代码来更详细的了解一下array。

//STL -- array
#include <iostream>
#include<array>
#include<ctime>

namespace t01
{
	using std::array;
	using std::cout;
	using std::cin;
	using std::clock;
void test()
{
	const int size = 1000;
	array<long, size> tmp;
	long tmp2[size];
	cout << "If we don't initial the array,let's check the first ten datas of array and original array\n";
	cout << "STL:\n";
	for (int i = 0; i < 10; i++)
	{
		cout << tmp[i] << " ";
	}
	cout << "\n";
	cout << "Original:\n";
	for (int i = 0; i < 10; i++)
	{
		cout << tmp2[i] << " ";
	}
	cout << "\n";
	cout << "Now we initial it\n";
	auto TarrayStart = clock();
	for (int i = 0; i < size; i++)
	{
		tmp[i] = i;
	}
	auto TarrayEnd = clock();
	
	auto TOStart = clock();
	for (int i = 0; i < size; i++)
	{
		tmp[i] = i;
	}
	auto TOEnd = clock();

	cout << "We use " << TarrayEnd - TarrayStart << " ms to initial STL array\n";
	cout << "We use " << TOStart - TOEnd << " ms to initial original array\n";

	cout << "The size of array: " << tmp.size() << "\n";
	cout << "The first data's memory location is:" << tmp.data() << "\n";
	cout << "The first data's value is:" << tmp.at(0) << "\n";
	cout << "The last data's value is:" << tmp.back() << "\n";
	cout << "For iter:\n";
	cout << "\tThe first data's pointer:" << *(tmp.begin()) << "\n";
}
}

int main()
{
	t01::test();
	return 0;
}

代码运行结果:
在这里插入图片描述

通过上述代码以及运行结果来看,C++ STL中的array与原生的array在使用上基本上与原生array无差别。但是通过封装的思想我们可以更好的使用一些容器,让我们代码更加清晰明了,而且泛型化的封装也使得我们使用这个类型的时候更加随意。

猜你喜欢

转载自blog.csdn.net/hbn13343302533/article/details/90139794