map和set的介绍和使用

一.关联式容器

在之前,我们已经接触过STL中的部分容器,比如:vector,list,deque等,这些容器统称为序列式容器,因为其底层为线性序列的数据结构,里面存储的是元素本身。那什么是关联式容器?它与序列式容器有什么区别?

关联式容器也是用来存储数据的,与序列式容器不同的是,其里面存储的是<key, value>结构的键值对,在数据检索时比序列式容器效率更高。比如 : map/set/unordered_map/unordered_set
map/set底层使用红黑树实现,unordered_map/unordered_set使用哈希表实现

二. set

(1). set是STL中一个很有用的容器,用来存储同一种数据类型的数据结构(可以称之为K的模型),基本功能与数组相似。
(2). set与数组不同的是,在set中每个元素的值都是唯一的。
(3). set插入数据时,能够根据元素的值自动进行排序。
(4). set中元素的值并不能直接被改变。(会修改底层红黑树的结构)
(5). set插入数据时不能插入重复数据

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;

set 构造

// 构造空的set
set (const Compare& comp = Compare(), const Allocator& = Allocator());
// 用[first, last)区间中的元素构造set
set (InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator() );
// set的拷贝构造
set ( const set<Key,Compare,Allocator>& x);
#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> first; // 构造一个空的set
	int arr[] = { 1,2,3 };
	set<int> second(arr,arr + 3); // 区间构造
	set<int> third(second); // 拷贝构造
	set<int> fourth(second.begin(),second.end()); // 迭代器区间构造
}

set 修改

// 在set中插入元素x,实际插入的是<x, x>构成的键值对
// 如果插入成功,返回<该元素在set中的位置,true>
// 如果插入失败,说明x在set中已经存在,返回<x在set中的位置,false>
pair<iterator,bool> insert(const value_type& x)
// 在 position 位置插入val,返回新插入元素的位置或已经存在元素的位置
iterator insert (iterator position, const value_type& val);
// 插入迭代器[first,last)区间的元素
template <class InputIterator>
  void insert (InputIterator first, InputIterator last);
  
// 删除set中position位置上的元素
void erase (iterator position)
// 删除set中值为x的元素,返回删除的元素的个数
size_type erase (const key_type& x)
// 删除set中[first, last)区间中的元素
void erase (iterator first, iterator last)

// 交换set中的元素
void swap (set<Key,Compare,Allocator>& st)

// 将set中的元素清空
void clear()

// 返回set中值为x的元素的位置,无x 返回set::end
iterator find (const key_type& x) const

// 返回set中值为x的元素的个数,返回值只能为0,1
size_type count (const key_type& x) const

// insert 的使用

注意 : 在 position 位置插入元素时插入的元素并不一定在 position 位置,因为插入元素时会根据 Compare 提供的方法进行排序

#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> s;
	set<int>::iterator it;
	pair<set<int>::iterator, bool> ret;
	// 插入元素
	for (int i = 1; i <= 5; i++) s.insert(i);
	// 3已经存在,插入失败,返回false,ret.first指向已经存在3的位置
	ret = s.insert(3);
	if (ret.second == false) it = ret.first;

	s.insert(it,2);
	s.insert(it,0);
	s.insert(it,10);
	
	// 迭代器区间构造
	int a[] = {-1,-2,-5};
	s.insert(a,a + 3);

	for (it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
// 输出结果为
// -5 -2 -1 0 1 2 3 4 5 10

// erase使用

#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> s;
	set<int>::iterator it;
	for (int i = 1; i <= 5; i++) s.insert(i);

	it = s.begin();
	++it;
	// 删除2
	s.erase(it);
	// 删除3,返回删除元素的个数
	size_t ret = s.erase(3);
	cout << ret << endl;
	// it指向4的位置
	it = s.find(4);
	// 删除4~5
	s.erase(it,s.end());

	for (it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
// 输出结果为 1
s.erase(3); 等价于

auto pos = s.find(3);
if(pos != s.end())
{
	s.erase(pos);
}

// swap使用

在C++98中,下面两种写法是有差异的
s1.swap(s2); // 只需要交换两树的根节点即可
swap(s1,s2); // 需要进行深拷贝

#include<iostream>
#include<set>
using namespace std;
int main()
{
	int a[] = {1,2,3,4,5,6};
	set<int> s1(a,a + 3);
	set<int> s2(a + 3,a + 6);
	
	s1.swap(s2);
}
// 输出结果
// 4 5 6
// 1 2 3

// clear使用

#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> s;
	s.insert(100);
	s.insert(200);
	print(s);
	s.clear();
	s.insert(400);
	s.insert(500);
	print(s);
}
// 输出结果
// 100 200
// 400 500

set 容量和迭代器

// 检测set是否为空,空返回true,否则返回true
bool empty() const
// 返回set中有效元素的个数
size_type size() const 
// 返回set中起始位置元素的迭代器
iterator begin()
// 返回set中最后一个元素后面的迭代器
iterator end()
// 返回set中起始位置元素的const迭代器
const_iterator cbegin() const
// 返回set中最后一个元素后面的const迭代器
const_iterator cend() const 
// 
reverse_iterator rbegin() 
reverse_iterator rend() 
const_reverse_iterator crbegin() const
const_reverse_iterator crend() const

使用

#include<iostream>
#include<set>
using namespace std;
int main()
{
	set<int> s;
	set<int>::iterator it;
	set<int>::reverse_iterator rit;
	for (int i = 0; i < 5; i++) s.insert(i);
	// 正向迭代器
	for (it = s.begin(); it != s.end(); it++)
	{
		// *it += 1; 不能修改
		cout << *it << " ";
	}
	cout << endl;
	// 反向迭代器
	for (rit = s.rbegin(); rit != s.rend(); rit++)
	{
		cout << *rit << " ";
	}
	cout << endl;
}

三.multiset

multiset 和 set 的最主要区别在于 multiset 中的元素可以重复

#include<iostream>
#include<set>
using namespace std;
int main()
{
	multiset<int> m;

	for (int i = 0; i <= 5; i++) m.insert(i);
	// multiset允许键值冗余
	m.insert(3);
	m.insert(4);
	m.insert(5);

	multiset<int>::iterator it;

	for (it = m.begin(); it != m.end(); it++)
	{
		// *it += 1; 注意不能修改
		cout << *it << " ";
	}
	cout << endl;

	// find查找的val有多个的时候,找到的是中序的第一个
	multiset<int>::iterator pos = m.find(3);
	while (*pos == 3)
	{
		cout << *pos << endl;
		++pos;
	}

	cout << m.count(3) << endl;

	// erase会删除所有的 3
	m.erase(3);
	for (it = m.begin(); it != m.end(); it++)
	{
		// *it += 1; 注意不能修改
		cout << *it << " ";
	}
	cout << endl;
}

四.map

(1). map是关联容器,它按照特定的次序(按照key来比较)存储由键值key和值value组合而成的元素。
(2). 在map中,键值key通常用于排序和惟一地标识元素,而值value中存储与此键值key关联的内容。键值key和值value的类型可能不同,并且在map的内部,key与value通过成员类型value_type绑定在一起,为其取别名称为pair:typedef pair value_type;
(3). 在内部,map中的元素总是按照键值key进行比较排序的。
(4). map中通过键值访问单个元素的速度通常比unordered_map容器慢,但map允许根据顺序对元素进行直接迭代(即对map中的元素进行迭代时,可以得到一个有序的序列)。
(5). map支持下标访问符,即在[]中放入key,就可以找到与key对应的value。
(6). map通常被实现为红黑树

map模板参数

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;

(1). key: 键值对中key的类型
(2). T: 键值对中value的类型
(3). Compare: 比较器的类型,map中的元素是按照key来比较的,缺省情况下按照小于来比较,一般情况下(内置类型元素)该参数不需要传递,如果无法比较时(自定义类型),需要用户自己显式传递比较规则(一般情况下按照函数指针或者仿函数来传递)
(4). Alloc:通过空间配置器来申请底层空间,不需要用户传递,除非用户不想使用标准库提供的空间配置器
(5). 注意:在使用map时,需要包含头文件

map构造

// 构造一个空的map
explicit map (const key_compare& comp = key_compare(),
              const allocator_type& alloc = allocator_type())
// 使用迭代器区间构造
template <class InputIterator>
  map (InputIterator first, InputIterator last,
       const key_compare& comp = key_compare(),
       const allocator_type& alloc = allocator_type());
// 拷贝构造
map(const map& x);
#include<iostream>
#include<map>
using namespace std;
int main()
{
	// 构造一个空map
	map<char, int> m;
	m['a'] = 10;
	m['b'] = 20;
	m['c'] = 30;
	// 迭代器区间初始化
	map<char, int> m2(m.begin(),m.end());
	// 拷贝构造
	map<char, int> m3(m2);
}

map修改

注意 : value_type 是 pair 结构体

typedef pair<const Key, T> value_type;
// 在map中插入键值对x,注意x是一个键值对,返回值也是键值对
//iterator代表新插入元素的位置或已经存在的位置,bool代表插入是否成功
pair<iterator,bool> insert (const value_type& x)
// 删除position位置上的元素
void erase (iterator position)
// 删除键值为x的元素,返回删除元素的个数
size_type erase (const key_type& x)
// 删除[first, last)区间中的元素
void erase (iterator first,iterator last)
// 交换两个map中的元素
void swap (map<Key,T,Compare,Allocator>& mp)
// 将map中的元素清空
void clear()
// 在map中插入key为x的元素,找到返回该元素的位置的迭代器,否则返回end
iterator find (const key_type& x)
// 在map中插入key为x的元素,找到返回该元素的位置的const迭代器,否则返回cend
const_iterator find (const key_type& x) const
// 返回key为x的键值在map中的个数,注意map中key是唯一的,因此该函数的返回值要么为0,要么为1,因
//此也可以用该函数来检测一个key是否在map中
size_type count (const key_type& x) const

insert 使用

// make_pair函数模板
template <class T1,class T2>
pair<T1,T2> make_pair (T1 x, T2 y)
{
    return ( pair<T1,T2>(x,y) );
}
#include<iostream>
#include<map>
using namespace std;
int main()
{
	map<int, double> m;
	// 调用pair的构造函数,构造一个匿名对象插入
	m.insert(pair<int,double>(1,1.1));
	m.insert(pair<int, double>(2, 2.2));
	m.insert(pair<int, double>(3,3.3));
	// 调用函数模板,构造对象更方便
	m.insert(make_pair(4,4.4));

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

erase 使用

#include<iostream>
#include<map>
using namespace std;
int main()
{
	map<char, int> m;

	m['a'] = 10;
	m['b'] = 20;
	m['c'] = 30;
	m['d'] = 40;
	m['e'] = 50;
	m['f'] = 60;

	auto it = m.find('b');
	if (it != m.end())
	{
		m.erase(it);
	}

	m.erase('c');

	it = m.find('e');
	if (it != m.end())
	{
		m.erase(it,m.end());
	}

	for (it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << ":" << it->second << endl;
	}
}
// 输出结果
// a : 10
// d : 40

swap使用

// swap maps
#include <iostream>
#include <map>
using namespace std;
int main ()
{
  map<char,int> foo,bar;

  foo['x']=100;
  foo['y']=200;

  bar['a']=11;
  bar['b']=22;
  bar['c']=33;

  foo.swap(bar);

  cout << "foo contains:\n";
  for (map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it)
    cout << it->first << " => " << it->second << '\n';

  cout << "bar contains:\n";
  for (map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
    cout << it->first << " => " << it->second << '\n';

  return 0;
}
// foo contains:
// a => 11
// b => 22
// c => 33
// bar contains:
// x => 100
// y => 200

clear使用

// map::clear
#include <iostream>
#include <map>
using namespace std;
int main ()
{
  map<char,int> mymap;

  mymap['x']=100;
  mymap['y']=200;
  mymap['z']=300;

  cout << "mymap contains:\n";
  for (map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    cout << it->first << " => " << it->second << '\n';

  mymap.clear();
  mymap['a']=1101;
  mymap['b']=2202;

  cout << "mymap contains:\n";
  for (map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    cout << it->first << " => " << it->second << '\n';
    
  return 0;
}
// mymap contains:
// x => 100
// y => 200
// z => 300
// mymap contains:
// a => 1101
// b => 2202

count使用(只能返回1和0)

// map::count
#include <iostream>
#include <map>
using namespace std;
int main ()
{
  map<char,int> mymap;
  char c;

  mymap ['a']=101;
  mymap ['c']=202;
  mymap ['f']=303;

  for (c='a'; c<'h'; c++)
  {
    cout << c;
    if (mymap.count(c)>0)
      cout << " is an element of mymap.\n";
    else 
      cout << " is not an element of mymap.\n";
  }

  return 0;
}
// a is an element of mymap.
// b is not an element of mymap.
// c is an element of mymap.
// d is not an element of mymap.
// e is not an element of mymap.
// f is an element of mymap.
// g is not an element of mymap

map应用场景1 : 统计出现次数

#include<iostream>
#include<map>
using namespace std;
void test1()
{
	map<string, int> countMap;
	string arr[] = { "sort","left","left","right","left","left","right","sort","right" };
	for (const auto& e : arr)
	{
		// map<string,int>::iterator it
		auto it = countMap.find(e);
		// 已经存在,不是第一次插入
		if (it != countMap.end())
		{
			it->second++;
		}
		// 第一次插入
		else
		{
			countMap.insert(make_pair(e,1));
		}
	}
	for (auto it = countMap.begin(); it != countMap.end(); it++)
		cout << it->first << " " << it->second << endl;
}
void test2()
{
	map<string,int> countMap;
	string arr[] = { "sort","left","left","right","left","left","right","sort","right" };
	for (const auto& e : arr)
	{
		// pair<iterator,bool> it
		auto it = countMap.insert(make_pair(e,1));
		// 不是第一次插入
		if (it.second == false) it.first->second++;
	}
	for (auto it = countMap.begin(); it != countMap.end(); it++)
		cout << it->first << " " << it->second << endl;
}
void test3()
{
	map<string, int> countMap;
	string arr[] = { "sort","left","left","right","left","left","right","sort","right" };
	for (const auto& e : arr)
	{
		countMap[e]++;
	}
	for (auto it = countMap.begin(); it != countMap.end(); it++)
		cout << it->first << " " << it->second << endl;
}
void test4()
{
	
}
int main()
{
	//test1();
	//test2();
	//test3();
}

operator[] 原型

mapped_type& operator[] (const key_type& k)
{
	(*((this->insert(make_pair(k,mapped_type()))).first)).second;
}

map应用场景2 : 按照单词出现次数进行排序

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;
struct Compare
{
	bool operator()(map<string, int>::iterator x, map<string, int>::iterator y)const
	{
		return x->second < y->second;
	}	
};
int main()
{
	map<string, int> countMap;
	string arr[] = { "sort","left","left","right","left","left","right","sort","right" };
	for(const auto& e : arr)
	{
		countMap[e]++;
	}
	// vector中存放节点的迭代器,按照自定义的排序(次数排序),排序迭代器
	vector<map<string, int>::iterator> v;
	for (auto it = countMap.begin(); it != countMap.end(); it++)
	{
		v.push_back(it);
	}
	sort(v.begin(),v.end(),Compare());
	// 使用 map 根据次数进行排序
	map<int, string> sortMap;
	for (const auto& e : countMap)
	{
		sortMap.insert(make_pair(e.second,e.first));
	}
	// 使用 set 根据次数排序
	set<map<string, int>::iterator, Compare> s;
	for (auto it = countMap.begin(); it != countMap.end(); it++)
	{
		s.insert(it);
	}
	// 使用优先级队列依次选出次数
	priority_queue<map<string, int>::iterator, vector<map<string, int>::iterator>, Compare> pq;
	for (auto it = countMap.begin(); it != countMap.end(); it++)
	{
		pq.push(it);
	}
}

map容量和迭代器

// begin : 首元素的位置,end : 最后一个元素的下一个位置
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
// 反向迭代器,rbegin在end位置,rend在begin位置,其++和--操作与begin和end操作移动相反
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
// 检测 map 中的元素是否为空,是返回true,否则返回false
bool empty () const;
// 返回map中有效元素的个数
size_type size() const;
// 返回key对应的value
mapped_type& operator[] (const key_type& k);

使用

#include<iostream>
#include<map>
using namespace std;
int main()
{
	map<int, int> m;
	m.insert(make_pair(1,1));
	m.insert(make_pair(2,2));
	m.insert(make_pair(3,3));
	m.insert(make_pair(4,4));
	// size为4
	cout << m.size() << endl;
	// 正向迭代器遍历
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	cout << endl;
	// 反向迭代器遍历
	for (map<int, int>::reverse_iterator it = m.rbegin(); it != m.rend(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	cout << endl;
	// operator[]
	cout << m[1] << endl;
	cout << m[2] << endl;
	cout << m[3] << endl;
	cout << m[4] << endl;
}

五. multimap

multimap和map的唯一不同就是:map中的key是唯一的,而multimap中key是可以重复的

#include<iostream>
#include<map>
using namespace std;
int main()
{
	multimap<int, int> m;
	m.insert(make_pair(1, 1));
	m.insert(make_pair(1, 2));
	m.insert(make_pair(1, 3));
	m.insert(make_pair(2, 4));
	m.insert(make_pair(2, 5));

	for (multimap<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	cout << endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值