学习C++ primer 之路 - ( 第十六章 之 STL模板之顺序容器)

STL多种容器以及结构

1.Array(顺序容器)

结构图:

长度大小是规定死的,无法动态扩充空间

定义:

#include <array>
array<double,10>ary = {1,2,3,4,5,6,7,8,9,10}; //必须有第二个参数,要指定有多大

函数:

1.get

这是一个全局的函数并不是array模板所持有的

get(元素偏移量,元素类型,数组中的元素书,从中选择的数组)

#include <array>
array<int,4>c0={1,2,3,4};
get<1>(c0);

2.begin()

获取数组第一个位置的迭代器

扫描二维码关注公众号,回复: 12604976 查看本文章

2.end()

获取数组最后一个位置的下一个位置的迭代器

3.size()

获取数组的长度

4.back()

获取数组最后一个元素的值

5.data()

获取第一个位置地址

6.front()

获取数组第一个位置的值

2.Vector(顺序容器)

结构图:

vector是一个向后扩充的容器,当它的空间不足时,扩充到原来的二倍,然后在不足时继续为原来的二倍.......

他们的地址也是一个连续的

vector总结传送门:https://blog.csdn.net/z1455841095/article/details/82668794

3.Deque(顺序容器)

双向开口可进可出的容器。

结构图:

这只是你表面看到的是这个样子:

其实更具体的是这个样子:

 前面第一个图 容器存入的是一个指向一段buffer空间的地址,具体是看这第二个图的样子。

当两端都填满时,若继续push_back添加元素,Deque容器会自动开辟一段buffer 用于存储并且有一个看似连续的地址指向它。

反之如果用push_front 也会开辟一段buffer

4.List(顺序容器)

双向链表

结构图

例代码:

#include<iostream>
#include <cstdlib>
#include <ctime>
#include <list>
#include <string>
#include <cstring>
#include <exception>
#include <array>
std::string get_a_target_string();
int main()
{
	using namespace std;
	srand(time(0));
	long value;
	cout << "how many elements: ";
	cin >> value;
	cout << "\ntest_list()........... \n";
	list<string>c;
	char buf[10];
	clock_t timeStart = clock();
	for (long i = 0; i < value; ++i)
	{
		try 
		{
			snprintf(buf, 10, "%d", rand());
			c.push_back(string(buf));
		}
		catch(exception & p)
		{
			cout << "i = " << i << " " << p.what() << endl;
			abort();//返回
		}
	}
	cout << "milli-seconds: " << (clock() - timeStart) << endl;

	cout << "list.size(): " << c.size() << endl;
	cout << "list.max_size(): " <<c.max_size() << endl;

	cout << "list.front(): " << c.front() << endl;
	cout << "list.back(): " << c.back() << endl;
	string target = get_a_target_string();
	timeStart = clock();
	auto pItem = find(c.begin(), c.end(), target);
	cout << "::find(), milli-seconds : " << (clock() - timeStart) << endl;
	if (pItem != c.end())
	{
		cout << "found, " << *pItem;
		cout << endl;
	}
	else {
		cout << "Not Found! " << endl;
	}

	timeStart = clock();
	c.sort();
	cout << "c.sort() milli-seconds : " << (clock() - timeStart) << endl;

	system("pause");
	return 0;
}
std::string get_a_target_string()
{
	using std::cin;
	using std::cout;
	int value;
	cout << "target (0~" << RAND_MAX << ": ";
	cin >> value;
	char buf[10];
	snprintf(buf, 10, "%d", value);
	return std::string(buf);
}

list有一个单独的sort成员。

空间利用率最高的顺序容器中效率最好的但是排序时候很慢

5.Forward_list(顺序容器)

单向链表

结构图:

 Forward_list有一个单独的sort常用

6.Stack(顺序容器)

栈容器 (它是一个先进后出的容器)

结构图:

 函数:

1.push

将元素推入栈中容器

2.pop

将元素将最后一个元素移除栈中


7.Queue(堆容器)

他是一个先进先出的容器

 函数:

1.push

将元素推入栈中(后面增加)

2.pop

总是将元素将第一个元素移除栈中

猜你喜欢

转载自blog.csdn.net/z1455841095/article/details/82696865