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个高频单词
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;
}