STL unordered_map 与 map的区别:
1.map底层实现原理是红黑树,unordered_map实现底层原理是哈希表
2.map对key值进行自动排序,unordered_map则是随机插入不排序
3.map在插入,查找上都比unordered_map更耗时间,但是内存消耗小;unordered_map则反之
void test1() {
map<char, int> first;
first['a'] = 97;
first['b'] = 98;
first['c'] = 99;
map<char, int>second(first);
map<char, int> third(second.begin(), second.end());
}
void test2() {
map<char, int> first;
first['a'] = 97;
first['b'] = 98;
first['c'] = 99;
map<char, int> second = first;
first = map<char, int>();
cout << "first.size() = " << first.size() << endl;
cout << "second.size() = " << second.size() << endl;
}
void test3() {
map<char, int> mymap;
mymap['a'] = 97;
mymap['b'] = 98;
mymap['c'] = 99;
for (map<char,int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
cout << "mymap[" << (*it).first << "] = " << (*it).second << endl;
}
}
void test4() {
map<char, int> mymap;
mymap['a'] = 97;
mymap['b'] = 98;
mymap['c'] = 99;
for (map<char,int>::reverse_iterator it = mymap.rbegin(); it != mymap.rend(); it++)
cout << "mymap[" << (*it).first << "] = " << (*it).second << endl;
}
void test5() {
map<char, int> mymap;
mymap['a'] = 97;
mymap['b'] = 98;
mymap['c'] = 99;
for (map<char, int>::const_reverse_iterator it = mymap.crbegin(); it != mymap.crend(); it++)
cout << "mymap[" << (*it).first << "] = " << (*it).second << endl;
}
void test6() {
map<char, int> mymap;
mymap['a'] = 97;
mymap['b'] = 98;
mymap['c'] = 99;
cout << "mymap.size() = " << mymap.size() << endl;
while (!mymap.empty()) {
cout << mymap.begin()->first << "->" << mymap.begin()->second << endl;
mymap.erase(mymap.begin());
}
cout << "mymap.size() = " << mymap.size() << endl;
cout << "mymap.max_size() = " << mymap.max_size() << endl;
}
void test7() {
map<char, int> mymap{ {'a',97},{'b',98},{'c',99} };
cout << mymap['a'] << endl;
cout << mymap[0] << endl;//如果是没有定义的表,那么默认取空值
mymap.at('a') = 111;//at可以找出表中对应的信息进行修改
cout << mymap['a'] << endl;
mymap.at('d') = 123;//这里会报错,因为at的本质是寻找,并不能进行创造
cout << mymap['d'] << endl;
}
void test8() {
//1.single element
std::map<char, int> mymap;
mymap.insert(std::pair<char, int>('a',97));
mymap.insert(std::pair<char, int>('b', 98));
//2.with hint 尽管是通过insert进行插入,但是在map中仍然会自动修改位,对it->first进行从小到大排列
mymap.insert(mymap.begin(), std::pair<char, int>('c', 99));
//3.range
std::map<char, int> newmap{ {'d',100}, {'e',101} };
mymap.insert(newmap.begin(), newmap.end());
//print mymap
for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
std::cout << "mymap[" << it->first << "]->" << it->second << "\n";
}
//print newmap
for (std::map<char, int>::iterator it = newmap.begin(); it != newmap.end(); it++) {
std::cout << "newmap[" << it->first << "]->" << it->second << "\n";
}
}
void test9() {
std::map<char, int> mymap{ {'d',100}, {'a',97},{'b',98},{'c', 99} };
//1.hint 这里迭代器的position其实本质上就是指针
std::map<char, int>::iterator it = mymap.find('b');
mymap.erase(it);
//2.hint val
mymap.erase(99);
//3.range
//mymap.erase(mymap.begin(), mymap.end());
//print mymap
for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
std::cout << "mymap[" << it->first << "]->" << it->second << "\n";
}
}
void test10() {
std::map<char, int> map1{ {'d',100}, {'a',97},{'b',98},{'c', 99} };
std::map<char, int> map2{ {'e',101} };
map1.swap(map2);
map1.clear();
map1.emplace('a', 97);
map1.emplace_hint(map1.end(), 'b', 98);
//print map1
for (std::map<char, int>::iterator it = map1.begin(); it != map1.end(); it++) {
std::cout << "map1[" << it->first << "]->" << it->second << "\n";
}
}
void test11() {
map<string, string> family{ {"wwx","son"},{"wj","dad"},{"lzq", "mom"} };
vector<string> people{ "wk", "wby", "wwx", "wj" };
for (auto& e : people) {
if (family.count(e))
cout << e << " is in my family as " << family.find(e)->second << endl;
else
cout << e << " is not in my family" << endl;
}
}
void test12() {
std::map<char, int> mymap{ {'a',97},{'b',98},{'c',99},{'d',100} };
std::map<char, int>::iterator itlow = mymap.lower_bound('b');
std::map<char, int>::iterator itupper = mymap.upper_bound('c');
mymap.erase(itlow, itupper);
//print mymap
for (std::map<char, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
std::cout << "mymap[" << it->first << "]->" << it->second << "\n";
}
}
map的结构是[key,value] ,在插入新元素的过程中会根据key进行自动排序,key值既可以是普通类型,指针类型,也可以是类类型,我们都可以对其进行排序。
#include
#include
#include
using namespace std;
/*
1.非自定义类类型
对于如同int char 此类型在map的Key值中进行排序,直接使用std::less, std::greater就可以解决
而对于指针类型,则只能采用函数对象
*/
struct Comp1
{
bool operator()(int *x, int *y)
{
return *x < *y;
}
};
void test1()
{
map<int, string, less<int>> mymap{{0, "aaa"}, {2, "fsda"}, {1, "as"}, {3, "ssgfss"}};
for (auto &e : mymap)
cout << e.first << ":" << e.second << endl;
cout << "----------------" << endl;
int *a1 = new int(0);
int *a2 = new int(2);
int *a3 = new int(1);
int *a4 = new int(3);
map<int *, string, Comp1> mymap2{{a1, "aaa"}, {a2, "fsda"}, {a3, "as"}, {a4, "ssgfss"}};
for (auto& e: mymap2)
cout << *e.first << ":" << e.second << endl;
}
/*
2.自定义类类型
针对自定义的类类型 如class Point类型, 就不能再使用std::less , std::greater 之类的函数
只能够自己重载运算符< , 或是定义函数对象
*/
class Point
{
int _x;
int _y;
int _multi;
public:
Point(int x, int y) : _x(x), _y(y), _multi(_x * _y) {}
int getMulti() const { return _multi; }
};
//方法一 重载运算符< 但注意对指针类型并不管用
bool operator<(const Point &lhs, const Point &rhs)
{
return lhs.getMulti() < rhs.getMulti();
}
//方法二 设置函数对象
struct Comp2
{
bool operator()(Point *lhs, Point *rhs)
{
return lhs->getMulti() < rhs->getMulti();
}
};
void test2()
{
map<Point, string> mymap1{{Point(1,2),"12"}, {Point(1,1),"11"}, {Point(3,1), "31"}, {Point(2,2),"22"}};
for (auto& e: mymap1)
cout << e.first.getMulti() << ":" << e.second << endl;
cout << "------------------" << endl;
Point *p1 = new Point(1,2);
Point *p2 = new Point(1,1);
Point *p3 = new Point(3,1);
Point *p4 = new Point(2,2);
map<Point*, string, Comp2> mymap2{{p1, "12"}, {p2, "11"}, {p3, "31"}, {p4,"22"}};
for(auto& e: mymap2)
cout << e.first->getMulti() << ":" << e.second << endl;
}
int main()
{
test2();
return 0;
}
相比于map,unordered_map中引入了桶的概念,其实也就是哈希表的原理,左边紫色方框表示桶,用链表连接的绿色方框表示插入的元素,用桶来装元素,如图:
void test1() {
unordered_map<string, string> hashmap{ {"China","Beking"},{"USA", "LA"},{"UA", "London"} };
cout << "The number of buckets:" << hashmap.bucket_count() << endl;
cout << "The number of Maxbuckets:" << hashmap.max_bucket_count() << endl;
cout << "遍历每个桶,从每个桶中遍历元素:" << endl;
for (int i = 0; i < hashmap.bucket_count(); i++) {
cout << i << "号桶有" << hashmap.bucket_size(i) << "个元素 ";
for (unordered_map<string, string>::iterator it = hashmap.begin(i); it != hashmap.end(i); it++) {
cout << it->first << "->" << it->second << " ";
}
cout << endl;
}
cout << "直接遍历所有桶中的元素 方法一:" << endl;
for (unordered_map<string, string>::iterator it = hashmap.begin(); it != hashmap.end(); it++) {
cout << it ->first << "->" << it->second << endl;
}
cout << "直接遍历所有桶中的元素 方法二:" << endl;
for (auto& e : hashmap)
cout << e.first << "->" << e.second << endl;
cout << "返回元素在哪一个桶:" << endl;
for (auto& e : hashmap) {
cout << e.first << "->" << e.second << "在" << hashmap.bucket(e.first) << "号桶" << endl;
}
}
void test2() {
unordered_map<string, string> hashmap{ {"China","Beking"},{"USA", "LA"},{"UA", "London"} };
cout << "桶的数量:" << hashmap.bucket_count() << endl;
hashmap.rehash(20);
cout << "after rehash, 桶的数量:" << hashmap.bucket_count() << endl;
cout << "加载因子为:" << hashmap.load_factor() << endl;
hashmap.reserve(3);
cout << "after reserve, 桶的数量:" << hashmap.bucket_count() << endl;
cout << "加载因子为:" << hashmap.load_factor() << endl;
cout << "最大加载因子为:" << hashmap.max_load_factor() << endl;
}
void test3() {
std::unordered_map<std::string, std::string> mymap;
mymap.insert({ "china", "Beking" });
mymap.insert({ "UK", "London" });
mymap.insert({ "USA", "LA" });
for (auto& e : mymap)
cout << e.first << "->" << e.second << endl;
}
这里将类存放进入hash表,需要自定义的有两个地方:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//类存放入哈希表
class Point
{
public:
Point(int x, int y)
: _x(x), _y(y)
{
_sum = x + y;
}
int _x;
int _y;
int _sum;
friend ostream &operator<<(ostream &os, const Point &lhs);
};
ostream &operator<<(ostream &os, const Point &lhs)
{
os << lhs._sum;
return os;
}
//自定义 PointEqual 也就是哈希表中key元素的存放比较
struct PointEqual{
bool operator()(const Point& lhs, const Point& rhs)const{
return (lhs._x==rhs._x) && (lhs._y==rhs._y);
}
};
//自定义PointHasher 也就是哈希函数
struct PointHasher
{
size_t operator()(const Point & rhs) const
{
return ((rhs._x * rhs._x) >> 1) ^
((rhs._y * rhs._y) >> 1);
}
};
void test1()
{
unordered_map<Point, int, PointHasher, PointEqual> myhashmap;
myhashmap.insert(make_pair(Point(1, 1), 1));
myhashmap.insert(make_pair(Point(2, 2), 2));
myhashmap.insert(make_pair(Point(3, 3), 3));
for (auto &e : myhashmap)
cout << e.first._sum << "," << e.second << endl;
}
int main()
{
test1();
return 0;
}