左程云算法笔记025

// map和哈希map的使用.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<map>
#include<string>
#include<unordered_map>
#include<functional>
using namespace std;

void Print(unordered_map<string,string>&Map)
{
	for (const auto& w : Map)
	{
		cout << "key值=" << w.first << "  value值=" << w.second << endl;
	}
}


class Node
{
public:
	Node(int v,string N):value(v),name(N){}

	string name;
	int value;
	
	bool operator==(const Node& p)const
	{
		return name == p.name && value == p.value;
	}


};


	size_t Nodehash(const Node& p)
	{
		return hash<string>()(p.name) ^ hash<int>()(p.value);
	}

	int main()
	{

		unordered_map<string, string>Map;
		Map.insert(pair<string, string>("xiaojien", "萧吉恩"));
		cout << Map.count("xiaojien") << endl;;
		cout << Map.count("x") << endl;;
		cout << Map["xiaojien"] << endl;
		Print(Map);
		cout << "---------------------------------" << endl;
		java的hashmap可以用put修改键值
		//Map.insert(pair<string, string>("xiaojien", "他是萧吉恩"));
		//cout << Map["xiaojien"] << endl;

		//Map.erase("xiaojien");
		at操作抛出异常
		Map.at("xiaojien");
		//cout<<"是空的" <<Map["xiaojien"]<< endl;
		cout << "-------------------------------------------------" << endl;

		string test1 = "xiaojien";
		string test2 = "xiaojien";
		cout << Map[test1] << endl;
		cout << Map[test2] << endl;


		unordered_map<int, string>Map2;
		Map2.insert(pair<int, string>(1234567, "我是1234567"));

		int a = 1234567;
		int b = 1234567;

		cout << (&a == &b) << endl;

		cout << Map2[a] << endl;
		cout << Map2[b] << endl;
		cout << "上面的代码在任何的语言中都是差不多的,哈希都是按值传递,哈希表的时间复杂度是O(1)级别" << endl;

		cout << "下面是非原生类型的对比,需要自定义对比运算符" << endl;


		unordered_map<Node, string, function<size_t(const Node& p)>>Map3(123,Nodehash);
		Node node1(1,"123");
		Node node2(2, "123");
		Map3.insert(pair<Node,string>(node1,"我进来了"));
		cout << Map3[node1] << endl;
		cout << Map3[node2] << endl;

		cout << "下面是有序表===========================" << endl;
		map<int, string>Map11;
		Map11.insert(pair<int, string>(3, "我是3"));
		Map11.insert(pair<int, string>(0, "我是3"));
		Map11.insert(pair<int, string>(7, "我是3"));
		Map11.insert(pair<int, string>(2, "我是3"));
		Map11.insert(pair<int, string>(5, "我是3"));
		Map11.insert(pair<int, string>(9, "我是3"));

		cout << Map11[3] << endl;
		//java的treeMap可以修改值,map不行
		Map11.insert(pair<int, string>(3, "我是4"));
		cout << Map11[3] << endl;

		auto x = Map11.begin();
		cout << x->first << endl;
		
		cout << "c++map 没有java的treemap强,没有lastkey,floorkey,类似的操作" << endl;
		cout << "map时间复杂度是log(n)级别," << endl;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值