C++进阶4:map 与 set 全攻略

引言

在 C++ STL 容器体系中,容器分为序列式容器(如 vector、list、deque)和关联式容器(如 map、set、unordered_map 等)两大核心类别。序列式容器以 “元素插入顺序” 为核心特征,而关联式容器则通过键(Key) 实现高效的查找、插入和删除操作,底层核心依赖红黑树(std::map/std::set)或哈希表(std::unordered_map/std::unordered_set)实现。

本文将聚焦 STL 中最经典的有序关联式容器 ——mapset,从基础概念、核心特性、常用接口,到 multiset/multimap 的差异,再结合 LeetCode 真题实战,完成一套结构化的 map/set 学习与实战指南,兼顾理论深度与工程实用性。

一、序列式容器 vs 关联式容器(核心对比)

作为博客的开篇铺垫,先明确两类容器的核心差异,帮助读者建立整体认知,为后续 map/set 的讲解奠定基础。

序列式容器,因为逻辑结构为线性序列的数据结构,两个位置存储的值之间⼀般没有紧密的关联关系,比如交换⼀下,他依旧是序列式容器。顺序容器中的元素是按他们在容器中的存储位 置来顺序保存和访问的。

关联式容器也是用来存储数据的,与序列式容器不同的是,关联式容器逻辑结构通常是非线性结构, 两个位置有紧密的关联关系,交换⼀下,他的存储结构就被破坏了。顺序容器中的元素是按关键字来保存和访问的。关联式容器有map/set系列和unordered_map/unordered_set系列。

二、set 系列容器全解析

在学习这方面的内容时推荐大家阅读文档进行学习。链接:https://legacy.cplusplus.com/reference/set/

2.1set的重点介绍

关于set的声明如下:

template < class T,                        // set::key_type/value_type
           class Compare = less<T>,        // set::key_compare/value_compare
           class Alloc = allocator<T>      // set::allocator_type
           > class set;
  • T就是set底层关键字的类型
  • set默认要求T支持小于比较,如果不支持或者想按自己的需求走可以自行实现仿函数传给第⼆个模 版参数
  • set底层存储数据的内存是从空间配置器申请的,如果需要可以自己实现内存池,传给第三个参 数。
  • ⼀般情况下,我们都不需要传后两个模版参数。
  • set底层是用红黑树实现,增删查效率是logN ,迭代器遍历是走的搜索树的中序,所以是有序的。

2.2set的构造

set的支持正向和反向迭代遍历,遍历默认按升序顺序,因为底层是⼆叉搜索树,迭代器遍历走的中序;支持迭代器就意味着支持范围for,set的iterator和const_iterator都不支持迭代器修改数据,修改关键字数据,破坏了底层搜索树的结构。不会重复插入。

int main()
{
	set<int> s;
	s.insert(5);
	s.insert(2);
	s.insert(7);
	s.insert(5);

	//set<int>::iterator it = s.begin();
	auto it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	return 0;
}

如果想要改成降序可以

	//降序
	// set<int,greater<int>> s;

2.3set的迭代器

set的迭代器是一个双向迭代器

2.4 set 的增删查(核心操作接口)

int main()
{
	set<int> s = { 4,2,7,2,8,5,9 };
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	// 删除最小值
	s.erase(s.begin());
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	// 直接删除x
	int x;
	/*cin >> x;
	int num = s.erase(x);
	if (num == 0)
	{
		cout << x << "不存在!" << endl;
	}
	else
	{
		cout << x << "删除成功!" << endl;
	}*/

	cin >> x;
	auto pos = s.find(x);
	if (pos != s.end())
	{
		// pos失效
		s.erase(pos);
		//cout << *pos << endl;
	}
	else
	{
		cout << x << "不存在!" << endl;
	}

	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	// 算法库的查找 O(N)
	auto pos1 = find(s.begin(), s.end(), x);

	// set自身实现的查找 O(logN)
	auto pos2 = s.find(x);

	// 利用count间接实现快速查找
	cin >> x;
	if (s.count(x))
	{
		cout << x << "在!" << endl;
	}
	else
	{
	cout << x << "不存在!" << endl;
	}

	return 0;
}

2.5lower_bound和upper_bound

lower_bound是返回大于等于val的迭代器

upper_bound是返回大于val的迭代器

这两个接口的设计很完美包容了我们所需要的左闭右开

int main()
{
	std::set<int> myset;
	for (int i = 1; i < 10; i++)
		myset.insert(i * 10); // 10 20 30 40 50 60 70 80 90
	for (auto e : myset)
	{
		cout << e << " ";
	}
	cout << endl;

	//// 实现查找到的[itlow,itup)包含[30, 60]区间 
	//// 返回 >= 30 
	//auto itlow = myset.lower_bound(30);
	//// 返回 > 60 
	//auto itup = myset.upper_bound(60);
	//// 删除这段区间的值 
	//myset.erase(itlow, itup);
	//for (auto e : myset)
	//{
	//	cout << e << " ";
	//}
	//cout << endl;


	//// 返回 >= 30
	//auto itlow = myset.lower_bound(30);
	//// 返回 > 50
	//auto itup = myset.upper_bound(50);

	// 返回 >= 25
	auto itlow = myset.lower_bound(25);
	// 返回 > 55
	auto itup = myset.upper_bound(55);

	// 删除这段区间的值
	myset.erase(itlow, itup);
	for (auto e : myset)
	{
		cout << e << " ";
	}
	cout << endl;


	return 0;
}

2.6multiset 和 set 的核心差异

multiset和set的使用基本完全类似,主要区别点在于multiset支持值冗余,我们上面所学习的insert/find/count/erase都围绕着支持值冗余有所差异。

int main()
{
	// 相比set不同的是,multiset是排序,但是不去重
	multiset<int> s = { 4,2,7,2,4,8,4,5,4,9 };
	auto it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	// 相比set不同的是,x可能会存在多个,find查找中序的第一个
	int x;
	cin >> x;
	auto pos = s.find(x);
	while (pos != s.end() && *pos == x)
	{
		cout << *pos << " ";
		++pos;
	}
	cout << endl;

	// 相比set不同的是,count会返回x的实际个数
	cout << s.count(x) << endl;

	//pos = s.find(x);
	//while (pos != s.end() && *pos == x)
	//{
	//	pos = s.erase(pos);
	//}
	//cout << endl;
	s.erase(x);

	it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;

	return 0;
}

练习题1:两个数组的交集

https://leetcode.cn/problems/intersection-of-two-arrays

题解:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> s1(nums1.begin(),nums1.end());
        set<int> s2(nums2.begin(),nums2.end());

        vector<int> ret;
        auto it1 = s1.begin();
        auto it2 = s2.begin();

        while(it1 != s1.end() && it2 != s2.end())
        {
            if (*it1 < *it2)
            {
                it1++;
            }
            else if (*it1 > *it2)
            {
                it2++;
            }
            else
            {
                ret.push_back(*it1);
                it1++;
                it2++;
            }
        }
        return ret;
    }
};

练习题2:环形链表2

https://leetcode.cn/problems/linked-list-cycle-ii

题解:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<ListNode*> s;
        ListNode* cur = head;
        
        while(cur)
        {
            auto ret = s.insert(cur);
            if(ret.second == false)
            return cur;
            
            cur = cur->next;
        }
        return nullptr;


    }
};

三、map 系列容器全解析

map键值对(Key-Value)关联式容器,核心特性是:存储唯一的键值对,按键自动升序排序,键(Key)唯一且不可修改,值(Value)可修改。multimap 作为变体,取消了 “键的唯一性” 限制,其余特性一致。

文档链接:https://legacy.cplusplus.com/reference/map/

3.1map的重点介绍

  • Key就是map底层关键字的类型,T是map底层value的类型
  • set默认要求Key支持小于比较,如果不支持或者需要的话可以自行实现仿函数传给第⼆个模版参数
  • map底层存储数据的内存是从空间配置器申请的。⼀般情况下,我们都不需要传后两个模版参数
  • map底层是用红⿊树实现,增删查改效率是O(logN) ,迭代器遍历是走的中序,所以是按key有序顺序遍历的
template < class Key,                                     // map::key_type
           class T,                                       // map::mapped_type
           class Compare = less<Key>,                     // map::key_compare
           class Alloc = allocator<pair<const Key,T> >    // map::allocator_type
           > class map;

3.2 pair 类型详解

相当于多分装了一层

3.3map的构造

int main()
{
	//map<string, string> dict;
	map<string, string> dict = { {"left", "左边"}, {"right", "右边"}, {"insert", "插入"},{ "string", "字符串" } };

	//pair<string, string> kv1("first", "第一个");
	//map<string, string> dict = {kv1, pair<string, string>("second", "第二个")};

	pair<string, string> kv1("first", "第一个");
	dict.insert(kv1);

	dict.insert(pair<string, string>("second", "第二个"));

	//函数模板,会自己推导自己构造
	dict.insert(make_pair("sort", "排序"));

	// C++11
	dict.insert({ "auto", "自动的" });

	// 插入时只看key,value不相等不会更新
	dict.insert({ "auto", "自动的xxxx" });

	map<string, string>::iterator it = dict.begin();
	while (it != dict.end())
	{
		// 可以修改value,不支持修改key
		//it->first += 'x';
		it->second += 'x';

		//cout << (*it).first <<":"<< (*it).second<< endl;
		cout << it->first << ":" << it->second << endl;
		//cout << it.operator->()->first << ":" << it.operator->()->second << endl;
		++it;
	}
	cout << endl;

	return 0;
}

3.4map的增删查改

关于pair我们还要特别注意在insert的接口中我们也看到了它的身影,但这里和前面不一样,是迭代器和布尔值的组合。

在看这个说明我们可以了解:

insert插⼊⼀个pair对象 。1、如果key已经在map中,插入失败,则返回⼀个pair对象,返回pair对象 first是key所在结点的迭代器,second是false  

2、如果key不在在map中,插入成功,则返回⼀个pair对象,返回pair对象 first是新插⼊key所在结点的迭代器,second是true 。

也就是说无论插⼊成功还是失败,返回pair对象的first都会指向key所在的迭代器 。那么也就意味着insert插入失败时充当了查找的功能,正是因为这一点,insert可以用来实现 operator[] 。

需要注意的是这里有两个pair,不要混淆了,一个是map底层红黑树节点中存的pair,另一个是insert返回值pair

// operator的内部实现 

mapped_type& operator[] (const key_type& k)
{
 // 1、如果k不在map中,insert会插⼊k和mapped_type默认值,同时[]返回结点中存储
mapped_type值的引⽤,那么我们可以通过引⽤修改返映射值。所以[]具备了插⼊+修改功能 
 // 2、如果k在map中,insert会插⼊失败,但是insert返回pair对象的first是指向key结点的
迭代器,返回值同时[]返回结点中存储mapped_type值的引⽤,所以[]具备了查找+修改的功能 
 pair<iterator, bool> ret = insert({ k, mapped_type() });
 iterator it = ret.first;
 return it->second;
}
int main()
{
 map<string, string> dict;
 dict.insert(make_pair("sort", "排序"));
 // key不存在->插⼊ {"insert", string()} 
 dict["insert"];
 // 插⼊+修改 
 dict["left"] = "左边";
 // 修改 
 dict["left"] = "左边、剩余";
 // key存在->查找 
 cout << dict["left"] << endl;
 return 0;
}
int main()
{
	// 利⽤[]插入+修改功能,巧妙实现统计水果出现的次数 
	string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜","苹果", "香蕉", "苹果", "香蕉" };
	map<string, int> countMap;
	for (const auto& str : arr)
	{
		// []先查找水果在不在map中 
		// 1、不在,说明水果第一次出现,则插入{水果, 0},同时返回次数的引用,++⼀下就变成1次了
		// 2、在,则返回水果对应的次数++ 
			countMap[str]++;
	}
	for (const auto& e : countMap)
	{
		cout << e.first << ":" << e.second << endl;
	}
	cout << endl;
	return 0;
}

练习题1:随机链表的复制

https://leetcode.cn/problems/copy-list-with-random-pointer

题解:

class Solution {
public:
 Node* copyRandomList(Node* head) {
 map<Node*, Node*> nodeMap;
 Node* copyhead = nullptr,*copytail = nullptr;
 Node* cur = head;
 while(cur)
 {
   if(copytail == nullptr)
 {
 copyhead = copytail = new Node(cur->val);
 }
 else
 {
 copytail->next = new Node(cur->val);
 copytail = copytail->next;
 }
 

 nodeMap[cur] = copytail;
 cur = cur->next;
 }

 cur = head;
 Node* copy = copyhead;
 while(cur)
 {
   if(cur->random == nullptr)
 {
 copy->random = nullptr;
 }
 else
 {
 copy->random = nodeMap[cur->random];
 }
 cur = cur->next;
 copy = copy->next;
 }
 return copyhead;
 }
};

练习题2:前K个高频单词

https://leetcode.cn/problems/top-k-frequent-words

题解:

class Solution {
public:
 struct Compare
 {
 bool operator()(const pair<string, int>& x, const pair<string, int>& y)
 const
 {
 return x.second > y.second;
 }
 };
 vector<string> topKFrequent(vector<string>& words, int k) {
 map<string, int> countMap;
 for(auto& e : words)
 {
 countMap[e]++;
 }
 vector<pair<string, int>> v(countMap.begin(), countMap.end());
 // 仿函数控制降序 
 stable_sort(v.begin(), v.end(), Compare());
 //sort(v.begin(), v.end(), Compare());
 
 // 取前k个 
 vector<string> strV;
 for(int i = 0; i < k; ++i)
 {
 strV.push_back(v[i].first);
}
 return strV;
 }
};

3.5multimap 和 map 的核心差异

multimapmap 的 “允许重复键” 版本,底层同样基于红黑树实现,二者的核心差异与 set/multiset 完全对应,且 multimap 有一个关键特性 ——不支持 [] 运算符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值