Map
1.特点:map存储key->value键值对,在一个map中仅存在唯一的key。可以实现快速插入、查找、遍历。内部由红黑树实现,所以查找速度上慢于哈希实现的unordered_map,但是元素按照key顺序排列,所以在对顺序有要求的问题中可以使用map。
2.常用方法:
#include <map>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
map<int, string> test;
test.insert(pair<int, string>(1, "a")); //插入元素,使用pair声明一个键值对
test.insert(map<int, string>::value_type(4, "b")); //插入元素,使用value_type方法声明一个键值对
test[3] = "c"; //插入元素,使用数组方法
//使用insert方法时,若插入的key已存在,则插入失败;使用数组方法,key已存在时覆盖
cout << test[4] << endl; //取元素
for (map<int, string>::iterator it = test.begin(); it != test.end(); ++it)
cout << it->first << " " << it->second << endl; //使用迭代器遍历
map<int, string>::iterator it = test.find(3); //查找key为3的值,若存在,返回对应迭代器;反之,返回test.end()
test.erase(it); //按照迭代器删除元素
test.erase(1); //按照key值删除元素
}
3.自定义数据结构的map
#include <map>
#include <iostream>
#include <algorithm>
#include <string>
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<Student, int> test;
test.insert(pair<Student, int>(Student(123, "xiaoming"), 2));
test.insert(pair<Student, int>(Student(242, "xiaoli"), 3));
cout << test.begin()->second; //输出为2
}
参考:
C++ map
Unordered_map
1.unordered_map与map的不同在于他的在key值无序,内部由哈希实现,根据哈希值判断元素是否相同,所以拥有更快的查找速度。
2.常用方法除内部无序外,与map类似。
3.自定义数据结构使用:
#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_map>
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<int> sh; //使用STL中hash<int>
return sh(a.id);
}
};
int main()
{
unordered_map<Student, int, MyHash, MyEqualTo> test;
test.insert(pair<Student, int>(Student(123, "xiaoming"), 2));
test.insert(pair<Student, int>(Student(242, "xiaoli"), 3));
cout << test.begin()->second; //输出为2
}
参考:C++
unordered_map