C++——set,map

一、 序列式容器和关联式容器

前⾯我们已经接触过STL中的部分容器如:string、vector、list、deque、array、forward_list等,这些容器统称为序列式容器, 因为逻辑结构为线性序列的数据结构,两个位置存储的值之间⼀般没有紧密的关联关系,⽐如交换⼀下,他依旧是序列式容器。顺序容器中的元素是按他们在容器中的存储位置来顺序保存和访问的。

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

map和set底层是红⿊树,红⿊树是⼀颗平衡⼆叉搜索树。
set是key搜索场景的结构,map是key/value搜索场景的结构。

二、set

1. 介绍

set和multiset参考⽂档

  • set的声明如下,T就是set底层关键字的类型
  • set默认要求T⽀持⼩于⽐较,如果不⽀持或者想按⾃⼰的需求⾛可以⾃⾏实现仿函数传给第⼆个模版参数
  • set底层存储数据的内存是从空间配置器申请的,如果需要可以⾃⼰实现内存池,传给第三个参数。⼀般情况下,我们都不需要传后两个模版参数。
  • set底层是⽤红⿊树实现,增删查效率是O(logN) ,迭代器遍历是⾛的搜索树的中序,所以是有序的。
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;

2. set的构造和迭代器

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

// empty (1) ⽆参默认构造
explicit set(const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// range (2) 迭代器区间构造
template <class InputIterator>
set(InputIterator first, InputIterator last,
const key_compare& comp = key_compare(),
const allocator_type & = allocator_type());
// copy (3) 拷⻉构造
set(const set& x);
// initializer list (5) initializer 列表构造
set(initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type());
// 迭代器是⼀个双向迭代器
iterator->a bidirectional iterator to const value_type
// 正向迭代器
iterator begin();
iterator end();
// 反向迭代器
reverse_iterator rbegin();
reverse_iterator rend()

3. set的增删查

Member types
key_type->The first template parameter(T)
value_type->The first template parameter(T)
// 单个数据插⼊,如果已经存在则插⼊失败
pair<iterator, bool> insert(const value_type& val);
// 列表插⼊,已经在容器中存在的值不会插⼊
void insert(initializer_list<value_type> il);
// 迭代器区间插⼊,已经在容器中存在的值不会插⼊
template <class InputIterator>
void insert(InputIterator first, InputIterator last);
// 查找val,返回val所在的迭代器,没有找到返回end()
iterator find(const value_type& val);
// 查找val,返回Val的个数
size_type count(const value_type& val) const;
// 删除⼀个迭代器位置的值
iterator erase(const_iterator position);
// 删除val,val不存在返回0,存在返回1
size_type erase(const value_type& val);
// 删除⼀段迭代器区间的值
iterator erase(const_iterator first, const_iterator last);
// 返回⼤于等val位置的迭代器
iterator lower_bound(const value_type& val) const;
// 返回⼤于val位置的迭代器
iterator upper_bound(const value_type& val) const;

例子:

void test01()
{
	set<int> s = { 10,2,3,4 };
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	s.insert(6);
	s.insert({ 6,2,8 });
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

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

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

	int x = 0;
	cin >> x;
	if (s.count(x))
	{
		cout << "删除成功" << endl;
	}
	else
	{
		cout << "失败" << endl;
	}

}

在这里插入图片描述

void test02()
{
	set<int> s;
	s.insert({ 10,5,6,4,3,20 });
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;
	//3 4 5 6 10 20
	s.erase(s.lower_bound(5), s.upper_bound(10));
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;
}

在这里插入图片描述

4. multiset和set的差异

multiset和set的使⽤基本完全类似,主要区别点在于multiset⽀持值冗余,那么insert/find/count/erase都围绕着⽀持值冗余有所差异。

void test03()
{
	multiset<int> s;
	s.insert({ 10,2,2,5,6,4,8,9,3,10 });
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;
	//2 2 3 4 5 6 8 9 10 10
	s.erase(2);
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	auto it = s.find(10);
	while (it != s.end())
	{
		s.erase(it);
		it = s.find(10);
	}
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;

	s.insert({ 5,5,5,8,9,71 });
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;
	cout << s.count(5) << endl;

	while (s.count(5))
	{
		s.erase(5);
	}
	for (auto e : s)
	{
		cout << e << " ";
	}
	cout << endl;
}

在这里插入图片描述

例题:

两个数组的交集

在这里插入图片描述

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> v;
        auto t1 = s1.begin();
        auto t2 = s2.begin();
        while(t1 != s1.end() && t2 != s2.end())
        {
            if(*t1 == *t2)
            {
                v.push_back(*t1);
                t1++;
                t2++;
            }
            else if(*t1 > *t2)
            {
                t2++;
            }
            else{
                t1++;
            }
        }
        return v;
    }
};

环形链表
在这里插入图片描述

/**
 * 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)
        {
            if(s.count(cur))
            {
                return cur;
            }
            else
            {
                s.insert(cur);
                cur = cur->next;
            }
        }
        return nullptr;
    }
};

三、map

1. 介绍

map和multimap参考⽂档

  • map的声明如下,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;

2. pair类型

map底层的红⿊树节点中的数据,使⽤pair<Key,T>存储键值对数据。

typedef pair<const Key, T> value_type;

template < class T1, class T2>
struct pair
{
	typedef T1 first_type;
	typedef T2 second_type;

	T1 first;
	T2 second;

	pair() : first(T1()), second(T2())
	{}

	pair(const T1& a, const T2& b) : first(a), second(b)
	{}

	template < class U, class V>
	pair(const pair<U, V>& pr) : first(pr.first), second(pr.second)
	{}
};

template < class T1, class T2>
inline pair<T1, T2> make_pair(T1 x, T2 y)
{
	return (pair<T1, T2>(x, y));
}

3. map的构造

map的⽀持正向和反向迭代遍历,遍历默认按key的升序顺序,因为底层是⼆叉搜索树,迭代器遍历⾛的中序;⽀持迭代器就意味着⽀持范围for,map⽀持修改value数据,不⽀持修改key数据,修改关键字数据,破坏了底层搜索树的结构。

// empty (1) ⽆参默认构造
explicit map(const key_compare & comp = key_compare(),
const allocator_type & alloc = allocator_type());

// range (2) 迭代器区间构造
template < class InputIterator>
map(InputIterator first, InputIterator last,
	const key_compare & comp = key_compare(),
	const allocator_type & = allocator_type());
// copy (3) 拷⻉构造
map(const map & x);

// initializer list (5) initializer 列表构造
map(initializer_list<value_type> il,
	const key_compare & comp = key_compare(),
	const allocator_type & alloc = allocator_type());

// 迭代器是⼀个双向迭代器
iterator->a bidirectional iterator to const value_type
// 正向迭代器
iterator begin();
iterator end();
// 反向迭代器
reverse_iterator rbegin();
reverse_iterator rend();

4. map的增删查

map增接⼝,插⼊的pair键值对数据,跟set所有不同,但是查和删的接⼝只⽤关键字key跟set是完全类似的,不过find返回iterator,不仅仅可以确认key在不在,还找到key映射的value,同时通过迭代还可以修改value。

Member types
key_type->The first template parameter(Key)
mapped_type->The second template parameter(T)
value_type->pair < const key_type, mapped_type>

// 单个数据插⼊,如果已经key存在则插⼊失败,key存在相等value不相等也会插⼊失败
pair<iterator, bool> insert(const value_type& val);
// 列表插⼊,已经在容器中存在的值不会插⼊
void insert(initializer_list<value_type> il);
// 迭代器区间插⼊,已经在容器中存在的值不会插⼊
template < class InputIterator>
void insert(InputIterator first, InputIterator last);
// 查找k,返回k所在的迭代器,没有找到返回end()
iterator find(const key_type & k);
// 查找k,返回k的个数
size_type count(const key_type & k) const;
// 删除⼀个迭代器位置的值
iterator erase(const_iterator position);
// 删除k,k存在返回0,存在返回1
size_type erase(const key_type & k);
// 删除⼀段迭代器区间的值
iterator erase(const_iterator first, const_iterator last);
// 返回⼤于等k位置的迭代器
iterator lower_bound(const key_type& k);
// 返回⼤于k位置的迭代器
const_iterator lower_bound(const key_type& k) const;

5. map的数据修改

前⾯提到map⽀持修改mapped_type数据,不⽀持修改key数据,修改关键字数据,破坏了底层搜索树的结构。

map第⼀个⽀持修改的⽅式时通过迭代器,迭代器遍历时或者find返回key所在的iterator修改,map还有⼀个⾮常重要的修改接⼝operator[],但是operator[]不仅仅⽀持修改,还⽀持插⼊数据和查找数据,所以他是⼀个多功能复合接⼝。

需要注意从内部实现⻆度,map这⾥把我们传统说的value值,给的是T类型,typedef为
mapped_type。⽽value_type是红⿊树结点中存储的pair键值对值。⽇常使⽤我们还是习惯将这⾥的T映射值叫做value。

Member types
key_type->The first template parameter(Key)
mapped_type->The second template parameter(T)
value_type->pair<const key_type, mapped_type>
// 查找k,返回k所在的迭代器,没有找到返回end(),如果找到了通过iterator可以修改key对应的
mapped_type值
iterator find(const key_type& k);
// ⽂档中对insert返回值的说明
// The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element with an equivalent key in the map.The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent key already existed.
// insert插⼊⼀个pair<key, T>对象
// 1、如果key已经在map中,插⼊失败,则返回⼀个pair<iterator,bool>对象,返回pair对象first是key所在结点的迭代器,second是false
// 2、如果key不在在map中,插⼊成功,则返回⼀个pair<iterator,bool>对象,返回pair对象first是新插⼊key所在结点的迭代器,second是true
// 也就是说⽆论插⼊成功还是失败,返回pair<iterator,bool>对象的first都会指向key所在的迭代器
// 那么也就意味着insert插⼊失败时充当了查找的功能,正是因为这⼀点,insert可以⽤来实现operator[]
// 需要注意的是这⾥有两个pair,不要混淆了,⼀个是map底层红⿊树节点中存的pair<key, T>,另⼀个是insert返回值pair<iterator,bool>pair<iterator, bool> insert(const value_type & val);

mapped_type& operator[] (const key_type& k);

// 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;
}

上面对于insert来说,可以总结为:
在这里插入图片描述

void test04()
{
	map<int, int> m;
	m.insert({1,10});
	m.insert(pair<int, int>(2, 20));
	m.insert(make_pair(3, 30));
	pair<int, int> p(5, 50);
	m.insert(p);
	auto it = m.begin();
	while (it != m.end())
	{
		cout << it->first << " " << it->second << endl;
		it++;
	}
}

在这里插入图片描述

void test05()
{
	map<string, int> m;
	string s[] = {"哈哈","卡卡","哦哦","全球","哈哈","卡卡","哦哦","全球","哈哈","哈哈"};
	for (auto& e : s)
	{
		auto it = m.find(e);
		if (it != m.end())
		{
			it->second++;
		}
		else
		{
			m.insert({e,1});
		}

		//m[e]++;
	}

	auto it = m.begin();
	while (it != m.end())
	{
		cout << it->first << ":" << it->second << endl;
		it++;
	}
	cout << endl;

}

在这里插入图片描述

void test06()
{
	map<string, int> m{ {"hehe",6},{"kk",8} };
	auto it = m.begin();
	while (it != m.end())
	{
		cout << it->first << ":" << it->second << endl;
		it++;
	}
	if(m.count("kk"))
	{
		m.erase("kk");
	}

	m.insert({ "hello", 6 });

	it = m.begin();
	while (it != m.end())
	{
		cout << it->first << ":" << it->second << endl;
		it++;
	}
}

在这里插入图片描述

void test07()
{
	map<int, string> m({ {6,"kk"},{8,"op"},{9,"ko"},{10,"mn"} });
	auto it = m.begin();
	while (it != m.end())
	{
		cout << it->first << ":" << it->second << endl;
		it++;
	}
	cout << endl;
	auto t = m.lower_bound(8);
	auto k = m.upper_bound(9);
	while (t != k)
	{
		cout << t->first << ":" << t->second << endl;
		t++;
	}
	cout << endl;
	m[6] = "ooo";
	m[66] = "hahaa";
	for (auto& e : m)
	{
		cout << e.first << ":" << e.second << endl;
	}
}

在这里插入图片描述

6. multimap和map的差异

multimap和map的使⽤基本完全类似,主要区别点在于multimap⽀持关键值key冗余, 那么insert/find/count/erase都围绕着⽀持关键值key冗余有所差异,这⾥跟set和multiset完全⼀样,⽐如find时,有多个key,返回中序第⼀个。

其次就是multimap不⽀持[],因为⽀持key冗余,[]就只能⽀持插⼊了,不能⽀持修改。

void test08()
{
	multimap<string, int> m;
	m.insert({ "sort",1 });
	m.insert({ "sort",2 });
	m.insert({ "sort",5 });
	m.insert({ "sort",7 });
	m.insert({ "sort",19 });
	for (auto& e : m)
	{
		cout << e.first << ":" << e.second << endl;
	}
}

在这里插入图片描述

随机链表的复制
在这里插入图片描述

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head)
    {
        if(head == nullptr)
        {
            return head;
        }    
        Node* cur = head;
        Node* copyhead = nullptr;
        Node* copytail = nullptr;
        map<Node*,Node*> m;
        while(cur)
        {
            if(copyhead == nullptr)
            {
                copyhead = copytail = new Node(cur->val);
            }
            else
            {
                copytail->next = new Node(cur->val);
                copytail = copytail->next;
            }
            //将源节点与拷贝结点一一复制
            m[cur] = copytail;
            cur = cur->next;
        }
        cur = head;
        copytail = copyhead;
        while(cur)
        {
            if(cur->random == nullptr)
            {
                copytail->random = nullptr;
            }
            else
            {
                copytail->random = m[cur->random];
            }
            cur = cur->next;
            copytail = copytail->next;
        }
        return copyhead;
    }
};

前K个高频单词

在这里插入图片描述

class Solution {
public:

    struct Compare
    {
        bool operator()(pair<string,int>& x,pair<string,int>& y)
        {
            return x.second > y.second ||( x.second == y.second && x.first < y.first);
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k)
    {
        map<string,int> s;
        for(auto& e : words)
        {
            s[e]++;
        }

        vector<pair<string,int>> v(s.begin(),s.end());
        sort(v.begin(),v.end(),Compare());

        vector<string> vv;
        for(int i = 0;i < k;i++)
        {
            vv.push_back(v[i].first);
        }
        
        return vv;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值