LeetCode刷题小结之map、unordered_map的使用

Map

1.特点:map存储key->value键值对,在一个map中仅存在唯一的key。可以实现快速插入、查找、遍历。内部由红黑树实现,所以查找速度上慢于哈希实现的unordered_map,但是元素按照key顺序排列,所以在对顺序有要求的问题中可以使用map。

2.常用方法:

#include 
#include 
#include 
#include 
using namespace std;
int main()
{
	map test;
	test.insert(pair(1, "a")); //插入元素,使用pair声明一个键值对
	test.insert(map::value_type(4, "b")); //插入元素,使用value_type方法声明一个键值对
	test[3] = "c"; //插入元素,使用数组方法
				   //使用insert方法时,若插入的key已存在,则插入失败;使用数组方法,key已存在时覆盖

	cout << test[4] << endl; //取元素
	for (map::iterator it = test.begin(); it != test.end(); ++it)
		cout << it->first << " " << it->second << endl;  //使用迭代器遍历
	
	map::iterator it = test.find(3); //查找key为3的值,若存在,返回对应迭代器;反之,返回test.end()

	test.erase(it); //按照迭代器删除元素
	test.erase(1);  //按照key值删除元素

}
3.自定义数据结构的map

#include 
#include 
#include 
#include 
using namespace std;
struct Student {
	int id;
	string name;
	Student (int _id, string _name):id(_id), name(_name){}
	//Student ():id(0), name(""){}

	bool operator  <(const Student& s) const{ //重载小于号运算符
		return id < s.id;
	}
};

int main()
{
	map test;
	test.insert(pair(Student(123, "xiaoming"), 2));
	test.insert(pair(Student(242, "xiaoli"), 3));
	
	cout << test.begin()->second; //输出为2
}
参考: C++ map

Unordered_map

1.unordered_map与map的不同在于他的在key值无序,内部由哈希实现,根据哈希值判断元素是否相同,所以拥有更快的查找速度。

2.常用方法除内部无序外,与map类似。

3.自定义数据结构使用:

#include 
#include 
#include 
#include 
using namespace std;
struct Student {
	int id;
	string name;
	Student (int _id, string _name):id(_id), name(_name){}
	//Student ():id(0), name(""){}

	bool operator  <(const Student& s) const{ //重载小于号运算符
		return id < s.id;
	}
};
class MyEqualTo {  //自定义等号
public:
	bool operator()(const Student& a, const Student& b)const {
		return a.id == b.id;
	}
};
class MyHash {  //自定义hash
public:
	size_t operator()(const Student& a)const {
		hash sh;        //使用STL中hash
		return sh(a.id);
	}
};
int main()
{
	unordered_map test;
	test.insert(pair(Student(123, "xiaoming"), 2));
	test.insert(pair(Student(242, "xiaoli"), 3));
	
	cout << test.begin()->second; //输出为2
}
参考:C++ unordered_map


你可能感兴趣的:(LeetCode刷题)