map和set

set

void test_set()
{
	set<int> s;
	s.insert(3);
	s.insert(1);
	s.insert(4);
	s.insert(3);
	s.insert(7);
	auto it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
}

set可以做到排序+去重。

*it不允许修改。

multiset  

允许键值冗余。

map 

operator* 返回的是节点中值的引用

operator-> 返回的是节点中值的指针   即为 pair<k,v>*

insert

map<int,int> m;
m.insert(pair<int,int>(1,1));//pair构造函数,构造一个匿名对象
m.insert(make_pair(2,2));    //函数模版构造一个pair对象。

find 

void test_map()
{
	string strs[] = { "apple","watermelon","Cherry","apple","Cherry" };
	map<string, int> countMap;
	for (auto& str : strs)
	{
		map<string, int>::iterator ret = countMap.find(str);
		if (ret != countMap.end())
			ret->second++;
		else
			countMap.insert(make_pair(str, 1));
	}
	for (auto& e : countMap)
		cout << e.first << " : "<<e.second << endl;
}

map   的迭代器中存的是pair 

 operator

void test_map()
{
	string strs[] = { "apple","watermelon","Cherry","apple","Cherry" };
	map<string, int> countMap;
	for (auto& str : strs)
	{
		countMap[str]++;
	}
	for (auto& e : countMap)
		cout << e.first << " : " << e.second << endl;
}

1.如果水果不在map中,则operator[]会插入pair<str,0>,返回印射对象(次数)的引用对其++

2.如果水果在map中,则operator[]返回水果对应的印射对象(次数)的引用,对其++

void test_map()
{
	string strs[] = { "apple","watermelon","Cherry","apple","Cherry" };
	map<string, int> countMap;
	for (auto& str : strs)
	{
		pair<map<string, int>::iterator, bool> ret = countMap.insert(make_pair(str, 1));
		if (ret.second == false)
			ret.first->second++;
	}
	for (auto& e : countMap)
		cout << e.first << " : " << e.second << endl;
}

 operator[]可以实现插入/修改/插入+修改

map<string,string> dict;
dict.insert(make_pair("sort","排序");
dict["string"];
dict["string"]="字符串";
dict["left"]="左";
mapped_type& operator[](const key_type& k)
{
	return (*((this->insert(make_pair(k, mapped_type()))).first)).second;
}

map中存的是pair<k,v>键值对。

mutimap没有operator[],因为有多个key时,不确定返回那个key对应的value;

692. 前K个高频单词

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=O83Ahttps://leetcode.cn/problems/top-k-frequent-words/description/

 vector<string> topKFrequent(vector<string>& words, int k) {
        map<string,int> countMap;
        for(auto e: words) countMap[e]++;
        multimap<int ,string,greater<int>> sortMap;
        for(auto kv:countMap) sortMap.insert(make_pair(kv.second,kv.first));
        vector<string> ret;
        multimap<int ,string>::iterator it=sortMap.begin();
        while(it!=sortMap.end())
        {
            if(k==0) break;
            ret.push_back(it->second);
            ++it;
            --k;
        }
        return ret;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值