set和map和unordered_set 和unorded_map 的基本操作

5 篇文章 0 订阅

1.set和unordered_set的
①插入
②读取
③删除
④创建一个降序set

这俩都是键不重复的集合,有序无序顾名思义。
使用erase(迭代器=find());删除一个键
使用*find(键号);访问对应键

#include<iostream>
#include<set>
#include<unordered_set>
using namespace std;
int main()
{
	set<int>st;
	unordered_set<int> ust;
	set<int, greater<int> > dst;
	st.insert(6);
	st.insert(5);
	st.insert(10);
	st.insert(2);
	cout << *st.find(2)<<endl;
	st.erase(st.find(2));
	cout << "set:" << endl;
	for (set<int>::iterator it = st.begin(); it != st.end(); it++)
		cout << *it << " ";
	cout << endl;

	ust.insert(6);
	ust.insert(5);
	ust.insert(10);
	ust.insert(2);
	cout << "unordered_set:" << endl;
	for (unordered_set<int>::iterator it = ust.begin(); it != ust.end(); it++)
		cout << *it << " ";
	cout << endl;

	dst.insert(6);
	dst.insert(5);
	dst.insert(10);
	dst.insert(2);
	cout << "d-unordered_set:" << endl;
	for (set<int>::iterator it = dst.begin(); it != dst.end(); it++)
		cout << *it << " ";
	cout << endl;
	return 0;
}

1.map和unordered_map的
①插入
②读取
③删除
④创建一个降序map
⑤查询一个键的值

这俩都是键不重复的集合,有序无序顾名思义。
使用erase(迭代器=find());删除一个键值对
使用find(键号)->second;访问对应键的值


如果是放入新数据,用数组下标的话会固定元素的位置 mp[1]=10;
如果需要自动排序的话,使用map,并且插入元素的时候使用
mp.insert(make_pair(1,10));
用这种方式插入的元素会自动进行升序排序
访问元素的时候也要注意,如果使用下标访问,如果访问到没有值的下标,那么会自动创建并且给予0的初值。
因此,访问元素的时候使用迭代器,才能正常的访问元素。

#include<iostream>
#include<set>
#include<unordered_set>
#include<map>
#include<unordered_map>
#include<string>
using namespace std;


int main() {
	map<int, string> mp;
	unordered_map<int, string> ump;
	map<int, string, greater<int>> dmp;
	mp.insert(make_pair(10, "s"));
	mp.insert(make_pair(5, "a"));
	mp.insert(make_pair(8, "g"));
	mp.insert(make_pair(2, "d"));


	ump.insert(make_pair(10, "s"));
	ump.insert(make_pair(5, "a"));
	ump.insert(make_pair(8, "g"));
	ump.insert(make_pair(2, "d"));

	dmp.insert(make_pair(10, "s"));
	dmp.insert(make_pair(5, "a"));
	dmp.insert(make_pair(8, "g"));
	dmp.insert(make_pair(2, "d"));

	cout << "mp.find(2):" << mp.find(2)->second << endl;
	mp.erase(mp.find(2));

	cout << "map:" << endl;
	for (map<int, string>::iterator it = mp.begin(); it != mp.end(); it++) {
		cout << it->first << " " << it->second;
		cout << endl;
	}
	cout << endl;

	cout << "unordered_map:" << endl;
	for (unordered_map<int, string>::iterator it = ump.begin(); it != ump.end(); it++) {
		cout << it->first << " " << it->second;
		cout << endl;
	}
	cout << endl;

	cout << "d-map:" << endl;
	for (map<int,string >::iterator it = dmp.begin(); it != dmp.end(); it++) {
		cout << it->first << " " << it->second;
		cout << endl;
	}
	cout << endl;

	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值