c++ map学习记录

1.map的本质是一类关联容器,其Key不可以修改,map的内部实现是一颗红黑树,因此其内部的数据都是有序的。

2.

  • map的功能是自动建立Key-value的意义对应的关系,值得注意的是key的类型必须支持<操作符
  • 根据key值可以快速的查找记录,其复杂度为log(N)

3.往map中插入元素

  • myMap.insert(pair<int, string>(1, "first"));
  • myMap.insert(map<int, string>::value_type(2, "second"));
  • myMap[1] = "first_"; //与上不同的是其可以覆盖key对应的value

4.insert的返回值是一个pair类型

pair<map<int, string>::iterator,bool>rMap=myMap.insert(map<int, string>::value_type(1, "first__"));

#include <iostream>
#include <map>
#include <string>

using namespace std;
int main()
{
	//创建一个map,以三种方式进行插入数据
	map<int, string>myMap;
	myMap.insert(pair<int, string>(1, "first"));
	myMap.insert(map<int, string>::value_type(2, "second"));
	myMap[1] = "first_";
	//insert的返回值
	pair<map<int, string>::iterator,bool>rMap=myMap.insert(map<int, string>::value_type(1, "first__"));
	cout << "insert operation:" <<boolalpha<< rMap.second << endl;
	//循环输出map
	cout << "myMap:" << endl;
	for (map<int, string>::iterator it = myMap.begin(); it != myMap.end(); it++) {
		cout << "Key:" << (*it).first << "    Value:" << (*it).second << endl;
	}
}

5.erase

注意erase函数

for(map<int,int>::iterator it = mapInt.begin(); it != mapInt.end();)
{
    if(it->second == 0)
    {
        mapInt.erase(it++);//涉及到后缀++其实返回的是一个it的副本
    }
    else
    {
        it++;
    }
}

6.重定义map内部的Compare函数

#include <iostream>
#include <map>
#include <string>

using namespace std;

struct cmpString {
	bool operator()(const string& s1, const string& s2) {
		return s1.length() < s2.length();
	}
};

int main()
{
	map<string, int, cmpString>myMap;
	myMap.insert(pair<string,int >("ZiLinMi", 72));
	myMap.insert(pair<string, int >("Bob", 79));
	myMap.insert(pair<string, int >("LiMin", 90));
	//循环输出map
	cout << "myMap:" << endl;
	for (map<string, int, cmpString>::iterator it = myMap.begin(); it != myMap.end(); it++) {
		cout << "Key:" << (*it).first << "    Value:" << (*it).second << endl;
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值