做公司網(wǎng)站用什么系統(tǒng)上海疫情最新數(shù)據(jù)
文章目錄
- 前言
- 一、map和set基礎(chǔ)知識(shí)
- 二、set與map使用示例
- 1.set去重操作
- 2.map字典統(tǒng)計(jì)
- 總結(jié)
前言
本章主要介紹map和set的基本知識(shí)與用法。
一、map和set基礎(chǔ)知識(shí)
map與set屬于STL的一部分,他們底層都是是同紅黑樹
來實(shí)現(xiàn)的。
①set常見用途是去重 ,set不允許修改key
值。
②map是<key,value>
結(jié)構(gòu),同樣也不允許修改key
值,map支持下標(biāo)訪問。
二、set與map使用示例
1.set去重操作
#include<iostream>
#include<set>
#include<string>
#include<vector>
using namespace std;int main() {vector<string> v1 = { "abandon","apple","banana","apple","orange" };set<string> s1(v1.begin(), v1.end());for (const auto& e : s1) {cout << e << " ";}return 0;
}
??可從下圖看出,對(duì)于重復(fù)的apple,set成功完成了去重。
2.map字典統(tǒng)計(jì)
#include<iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;int main() {string str("A blockhouse is a small castle that has four openings through which to shoot");vector<string> v1;size_t cur = 0;size_t pos = 0;while (pos != string::npos) {pos = str.find(" ", cur);string s(str, cur, pos - cur);cur = pos + 1;v1.emplace_back(s);}map<string, int> mp;for (const auto& e : v1) {mp[e]++;}for (const auto& e : mp) {cout << e.first << ":" << e.second << endl;}return 0;
}
??可以看到map很好統(tǒng)計(jì)了一句話中所有單詞出現(xiàn)的頻率。
總結(jié)
??本章主要介紹了map和set的基礎(chǔ)知識(shí),并且列舉了一些應(yīng)用場(chǎng)景。希望對(duì)讀者有所幫助。