c++(map和set)

set 

 set类的介绍

• set的声明如下,T就是set底层关键字的类型
• set默认要求T⽀持⼩于⽐较,如果不⽀持或者想按⾃⼰的需求⾛可以⾃⾏实现仿函数传给第⼆个模版参数
• set底层存储数据的内存是从空间配置器申请的,如果需要可以⾃⼰实现内存池,传给第三个参数。
• ⼀般情况下,我们都不需要传后两个模版参数。
• set底层是⽤红⿊树实现,增删查效率是 ,迭代器遍历是⾛的搜索树的中序,所以是有序
的。O(logN)
• 前⾯部分我们已经学习了vector/list等容器的使⽤,STL容器接⼝设计,⾼度相似,

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;

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();

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;

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#include<set>
int main()
{
	//去重+升序排序
	//set<int>s;
    //去重+自定义降序排序
	set<int, greater<int>>s;
	s.insert(1);
	s.insert(1);
	s.insert(2);
	s.insert(5);
	auto it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		it++;
	}
    //该迭代器不支持修改
	cout << endl;
	s.insert(s.begin(), 10);
	auto it1 = s.begin();
	while (it1!= s.end())
	{
		cout << *it1 << " ";
		it1++;
	}
	cout << endl;

    // 列表插⼊,已经在容器中存在的值不会插⼊
    //void insert(initializer_list<value_type> il);
	s.insert({ 2,3,4 });
	for (auto x : s)
	{
		cout <<x << " ";
	}
	cout << endl;

    //void insert(initializer_list<value_type> il);
    //走隐式类型转化,构造加拷贝构造优化为构造
	set<string> strset = { "sort", "insert", "add" };
    set<string> strset ({ "sort", "insert", "add" });//直接构造
	// 遍历string⽐较ascll码⼤⼩顺序遍历的
	for (auto& e : strset)
	{
		cout << e << " ";
	} cout << endl;
}

insert 

 //single element (1)    
pair<iterator,bool> insert (const value_type& val);
pair<iterator,bool> insert (value_type&& val);
//with hint (2)    
iterator insert (const_iterator position, const value_type& val);
iterator insert (const_iterator position, value_type&& val);
//range (3)    
template <class InputIterator>
  void insert (InputIterator first, InputIterator last);
//initializer list (4)    
void insert (initializer_list<value_type> il);

 find

const_iterator find (const value_type& val) const;//value_type->T
iterator       find (const value_type& val);

erase

(1)    iterator  erase (const_iterator position);
(2)    size_type erase (const value_type& val);//value_type->T
//size_type 无符号整形 删除成功返回1,失败返回0,兼容multiset
(3)    iterator  erase (const_iterator first, const_iterator last);

#include<iostream>
#include<set>
using namespace std;
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;
	} for (auto e : s)
	{
		cout << e << " ";
	} cout << endl;
	 return 0;
}
#include<iostream>
#include<set>
using namespace std;
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;
	int x;
	// 直接查找在利⽤迭代器删除x
	cin >> x;
	auto pos = s.find(x);
	if (pos != s.end())
	{
		s.erase(pos);
	} 
	else
	{
	cout << x << "不存在!" << endl;
	} for (auto e : s)
	{
		cout << e << " ";
	} cout << endl;
	 return 0;
}

#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> s = { 4,2,7,2,8,5,9 };
	for (auto e : s)
	{
		cout << e << " ";
	} cout << endl;
	
	int x;
	cin>>x;
	// 算法库的查找 O(N)
	auto pos1 = find(s.begin(), s.end(), x);
	// set⾃⾝实现的查找 O(logN)
	auto pos2 = s.find(x);
	 利⽤count间接实现快速查找
	//cin >> x;
    //count函数返回找到的个数
	//if (s.count(x))
	//{
	//	cout << x << "在!" << endl;
	//} else
	//{
	//	cout << x << "不存在!" << endl;
	//} return 0;
}

erase后迭代器失效

 upper_bound/lower_bound

// 返回⼤于等val位置的迭代器
iterator lower_bound(const value_type& val) const;
// 返回⼤于val位置的迭代器
iterator upper_bound(const value_type& val) const;

 multiset和set的差异

multiset仅排序,不去重

#include<iostream>
#include<set>
using namespace std;
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;
	// 相⽐set不同的是,erase给值时会删除所有的x
	s.erase(x);
	for (auto e : s)
	{
		cout << e << " ";
	} cout << endl;
	return 0;
}

erase

erase时,迭代器需要更新

 双向迭代器----不支持迭代器+数字

leetcode习题:

142. 环形链表 II   

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<ListNode*>s;
        ListNode* cur=head;
        while(cur)
        {
            if(s.count(cur))//环内循环查找到x
            {
                return cur;
            }
            else
            {
                s.insert(cur);//先构造了set的环
                cur=cur->next;
            }
        }
        return nullptr;
    }
};

 349.两个数组的交集

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int>n1;
        set<int>n2;
        for(int i=0;i<nums1.size();i++)
        {
            n1.insert(nums1[i]);
        }
        for(int i=0;i<nums2.size();i++)
        {
            n2.insert(nums2[i]);
        }
        
        int l1=0,l2=0;
        vector<int>result;
        auto it1=n1.begin();
        auto it2=n2.begin();
        while(it1!=n1.end()&&it2!=n2.end())
        {
            if(*it1==*it2)
            {
                result.push_back(*it1);
                it1++;
                it2++;
            }
            if(*it1<*it2)
            {
                it1++;
            }
            if(*it2<*it1)
            {
                it2++;
            }
        }
        return result;
    }
};

map

pair类型介绍

include<iostream>
#include<set>
using namespace std;
#include<map>

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", "第二个")};

	//typedef pair<const Key, T> value_type;
	pair<string, string> kv1("first", "第一个");
	dict.insert(kv1);

	//匿名对象
	dict.insert(pair<string, string>("second", "第二个"));

	//make_pair支持将一个结构变化成pair形式
	dict.insert(make_pair("sort", "排序"));

	// C++11
	//隐式类型转换
	dict.insert({ "auto", "自动的" });

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

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

		//cout << (*it).first <<":"<< (*it).second<< endl;
		cout << it->first << ":" << it->second << endl;//pair对象提取数据
		//cout << it.operator->()->first << ":" << it.operator->()->second << endl;
		++it;
	}
	cout << endl;

	return 0;
}

#include<iostream>
#include<set>
using namespace std;
#include<map>

int main()
{
		// 利⽤find和iterator修改功能,统计⽔果出现的次数
		string arr[] = { "苹果", "西⽠", "苹果", "西⽠", "苹果", "苹果", "西⽠",
		"苹果", "⾹蕉", "苹果", "⾹蕉" };
		map<string, int> countMap;
		for (const auto& str : arr)
		{
			// 先查找⽔果在不在map中
			// 1、不在,说明⽔果第⼀次出现,则插⼊{⽔果, 1}
			// 2、在,则查找到的节点中⽔果对应的次数++
			auto ret = countMap.find(str);
			if (ret == countMap.end())
			{
				countMap.insert({ str, 1 });
			} else
			{
			ret->second++;
			}
		} 
		for (const auto & e : countMap)
		{
			cout << e.first << ":" << e.second << endl;
		} 
		cout << endl;
		return 0;
}

#include<iostream>
#include<set>
using namespace std;
#include<map>

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

 

 insert

// ⽂档中对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>

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

multimap和map的差异

multimap和map的使⽤基本完全类似,主要区别点在于multimap⽀持关键值key冗余,那么
insert/find/count/erase都围绕着⽀持关键值key冗余有所差异,这⾥跟set和multiset完全⼀样,⽐如find时,有多个key,返回中序第⼀个。其次就是multimap不⽀持[],因为⽀持key冗余,[]就只能⽀持插⼊了,不能⽀持修改。

 equal_range

// map::equal_range
#include <iostream>
#include <map>

int main()
{
	std::map<char, int> mymap;

	mymap['a'] = 10;
	mymap['b'] = 20;
	mymap['c'] = 30;

	std::pair<std::map<char, int>::iterator, std::map<char, int>::iterator> ret;
	ret = mymap.equal_range('b');

	std::cout << "lower bound points to: ";
	std::cout << ret.first->first << " => " << ret.first->second << '\n';

	std::cout << "upper bound points to: ";
	std::cout << ret.second->first << " => " << ret.second->second << '\n';

	return 0;
}

 

leetcode习题:

692. 前K个高频单词

猜你喜欢

转载自blog.csdn.net/2301_79941274/article/details/143068615