2.1 栈、字符串
栈主要应用场景包括:括号匹配、表达式求值等。
#include <stack> # 库
stack<int> S; # 定义
S.push(i); # 存
int x = S.top(); # 读取并赋值
S.pop(); # 弹出不使用
字符串(string)
#include<iostream>
#include<string>
using namespace std;
int main()
{
// 构造字符串
string str1 = "hello";
string* str2 = new string("hello");
string str3 = "world";
//获取字符串长度
int length = str1.length();
//字符串连接
string str4 = str1 + str3;
//字符串比较 和字符数组不一样,这里可以直接比较
if (str1 < str3)
cout << "字符串比较:" << "str1<str2" << endl;
//获取字符串的第一个字符
string::const_iterator it = str1.begin();
cout << *it << endl;
//获取字符串的最后一个字符
it = str1.end();//end是指向最后一个字符后面的元素,而且不能输出,所以cout << *it << endl;这样输出会报错
it--;
cout << *it << endl;
//倒置串
reverse(str1.begin(), str1.end());
cout << "倒置串:" << str1 << endl;
//字符串转字符数组
string c = "abc123";
char *d = new char[20];
strcpy_s(d, strlen(d) + 1, c.c_str());//因为这里没有直接赋值,所以指针类型可以不用const char *
cout << "c:" << c << endl;
cout << "d:" << d << endl;
system("pause");
return 0;
}
结果:
2.2 哈夫曼树
哈夫曼树具有带权路径长度最小的特点,又称最优树。
构造哈夫曼树的过程中,需要选择当前节点集合中权值最小的两个节点。这里使用堆排序最优。这里便可以使用优先级队列实现堆排序的过程。通过构造小根堆,能够保证最小值在前面。
优先级队列
参考:https://blog.csdn.net/weixin_36888577/article/details/79937886
既然是队列那么需要先包含头文件#include <queue>
, 他和queue不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。
和队列基本操作相同:
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大根堆。
priority_queue<int> a; //大根堆
priority_queue<int, vector<int>, less<int> > a; //大根堆
priority_queue<int, vector<int>, greater<int> > c; //小根堆
#include<iostream>
#include <queue>
#include<functional>
#include<string>
using namespace std;
int main()
{
//对于基础类型 默认是大顶堆
priority_queue<int> a;
//等同于 priority_queue<int, vector<int>, less<int> > a;
// 这里一定要有空格,不然成了右移运算符↓
priority_queue<int, vector<int>, greater<int> > c; //这样就是小顶堆 需要#include<functional>
priority_queue<string> b;
//int 输入
for (int i = 0; i < 5; i++)
{
a.push(i);
c.push(i);
}
//int 输出
while (!a.empty())
{
cout << a.top() << ' ';
a.pop();
}
cout << endl;
while (!c.empty())
{
cout << c.top() << ' ';
c.pop();
}
cout << endl;
//string输入和输出
b.push("abc");
b.push("abcd");
b.push("cbd");
while (!b.empty())
{
cout << b.top() << ' '; // cout输出字符串需要#include<string>
b.pop();
}
cout << endl;
return 0;
}
结果: