unordered_map与unordered_set

map与set

这两个容器比较重要 ,在某些算法竞赛中经常用到


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

这里不讲基本函数,如果想要了解基本的,请看曾经文章。


一、set

1.set

set的底层是红黑树,set会使传入的数据进行升序排列。

#include<iostream>
#include<set>
#include<time.h>
#include<algorithm>
using namespace std;

void main() {
	srand((unsigned int)time(NULL));
	set<int>s;
	for (int i = 0; i < 20; i++) {
		s.insert(rand() % 100);
	}
	for (auto &i:s) {
		cout << i << " ";
	}
}

2.unordered_set

乱序集合,没啥用,还不如vector呢。不过性能比set容器好。

二、map

1.map

key值是m->first,value值是m->second.

#include<iostream>
#include<map>
#include<time.h>
#include<algorithm>
using namespace std;
void main() {
	map<int, string>mapStudent;
	mapStudent[123] = "student_first";
	mapStudent[456] = "student_second";

	// find 返回迭代器指向当前查找元素的位置否则返回map::end()位置
	map<int, string>::iterator iter = mapStudent.find(123);

	if (iter != mapStudent.end())
		cout << "Find, the value is" << iter->second << endl;
	else
		cout << "Do not Find" << endl;

	//迭代器刪除
	iter = mapStudent.find(123);
	mapStudent.erase(iter);

	//用关键字刪除
	int n = mapStudent.erase(123); //如果删除了会返回1,否則返回0

	//用迭代器范围刪除 : 把整个map清空
	mapStudent.erase(mapStudent.begin(), mapStudent.end());
	//等同于mapStudent.clear()

}
void main() {
	srand((unsigned int)time(NULL));
	map<int, int>m;
	
	m.insert(make_pair(1,2));
	m.insert(make_pair(11, 22));
	m.insert(make_pair(12, 28));
	cout << m[1] << " " << m[11] << " " << m[12] << endl;
}

2.unordered_map

需要加上头文件#include<unordered_map>

map: map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素,因此,对于map进行的查找,删除,添加等一系列的操作都相当于是对红黑树进行这样的操作,故红黑树的效率决定了map的效率。
unordered_map: unordered_map内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的

三、priority_queue

//升序队列
priority_queue <int,vector,greater > q;
//降序队列
priority_queue <int,vector,less >q;

top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容

默认的是输出时,最大的值在前面。

#include <iostream>
#include <queue>
using namespace std;

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) { x = a; }
    bool operator<(const tmp1& a) const
    {
        return x > a.x; //大顶堆
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b)
    {
        return a.x < b.x; //大顶堆
    }
};

int main()
{
    tmp1 a(1);
    tmp1 b(2);
    tmp1 c(3);
    priority_queue<tmp1> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while (!d.empty())
    {
        cout << d.top().x << '\n';
        d.pop();
    }
    cout << endl;

}


总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码有点萌

谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值