STL 容器(三) map和unordered_map


STL unordered_map 与 map的区别:
1.map底层实现原理是红黑树,unordered_map实现底层原理是哈希表
2.map对key值进行自动排序,unordered_map则是随机插入不排序
3.map在插入,查找上都比unordered_map更耗时间,但是内存消耗小;unordered_map则反之

一.map

1.MemberFunction
  • constructor
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());
}
  • operator =
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;
}

2.Iterator
  • std::begin()/end()
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;
	}
}
  • std::rbegin()/rend() ,r 表示reverse,表示从尾向前
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;
}
  • map.crbegin()/crend() cr 表示 const_reverse ,const修饰后不能修改
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;

}

3.Capacity
  • empty()/size()/max_size()
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;

}

4.Element access
  • operator[]/at
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;
}

5.Modifiers
  • insert
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";
	}
}
  • erase 清除数据可以通过位置、范围、值进行清除
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";
	}
}
  • swap/clear/emplace
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";
	}
}

6.Operations
  • find/count 注意find返回的是迭代器,count 则能从一个集合里面找到哪些是属于map的
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;
	}
}

在这里插入图片描述

  • lower_bound/upper_bound/equal_range lower_bound与upper_bound都是返回一个迭代器,用于先定一个最低和最高的范围,equal_range则是返回key相同的范围,本身无太大意义
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自定义排序

map的结构是[key,value] ,在插入新元素的过程中会根据key进行自动排序,key值既可以是普通类型,指针类型,也可以是类类型,我们都可以对其进行排序。

#include <iostream>
#include <set>
#include <map>
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;
}

三.unordered_map

相比于map,unordered_map中引入了桶的概念,其实也就是哈希表的原理,左边紫色方框表示桶,用链表连接的绿色方框表示插入的元素,用桶来装元素,如图:
在这里插入图片描述

1.buckets
  • bucket_count():因为是采用hash表方式存储,所以hashmap中元素的个数并不等于桶的个数;
    桶的个数是随机分配的,各个元素以链表形式连接在桶后面。
  • bucket.size(i):i表示第i个桶中拥有的元素的个数
  • begin(i):i表示第i个桶的begin iterator
  • end(i): i表示第i个桶的end iterator
  • bucket(it->first):表示*it元素在哪一号桶中
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;
	}

}

2.Hashpolicy
  • rehash(i):重新将桶的数量设置为 >= i
  • reserve():与rehash类似,重新规定桶的数量
  • load_factor():为加载因子,hashmap.size()/hashmap.bucket_count(),表示的是哈希表的填充程度;
    加载因子越大,哈希表充填得越多,冲突可能性增大,查找成功率增大
    加载因子越小,哈希表充填得越小,冲突可能性减小,查找成功率减小
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;
}

3.注意
  • 注意hashmap 是随机存放数据的,与数据插入(或存放)的位置没有关系
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;
}

在这里插入图片描述


四.unordered_map用法演示

这里将类存放进入hash表,需要自定义的有两个地方:

  • PointHasher: 哈希函数
  • PointEqual:也就是哈希表中的存放比较
#include <iostream>
#include <functional>
#include <vector>
#include <iterator>
#include <algorithm>
#include <unordered_map>
#include <map>
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值