C++容器map可以排序吗?
文章目錄
- map 定義
- 測試結(jié)果
- map排序
map 定義
哈希表(Hash Table,也叫散列表),是根據(jù)關(guān)鍵字key 直接進行訪問的數(shù)據(jù)結(jié)構(gòu),它通過把關(guān)鍵字值映射到表中一個位置(數(shù)組下標)來直接訪問,以加快查找關(guān)鍵字值的速度。這個映射函數(shù)稱為哈希(散列)函數(shù),存放記錄的數(shù)組叫做哈希(散列)表。
最簡單的應用是字母的映射,通過ASCII碼值。
#include<iostream> #include<string> using namespace std;int main() {int char_map[128]={0};string str="abcdefgaaxxy";for(int i=0;i<str.length();i++)char_map[str[i]]++;for(int i=0;i<128;i++){if(char_map[i]>0)cout<<(char)i<<" "<<i<<" "<<char_map[i]<<endl;}}測試結(jié)果
從左到右:字符,ASCII碼值,出現(xiàn)次數(shù)
例如,第一行的含義是:字母a,其ASCII碼值是97,出現(xiàn)的次數(shù)是3次。
map排序
map排序只能按照鍵排序,不能按照值排序
我是把map復制到vector中進行排序。
下面代碼是按鍵排序
打印結(jié)果
vector<pair<char,int> > ::iterator iter;//迭代器 for(iter=ans.begin();iter!=ans.end();iter++){cout<<(iter->first)<<" "<<iter->second<<endl;//輸出pair的元素}按鍵排序結(jié)果
鍵/值
A 3
B 2
C 1
D 3
F 2
G 2
H 2
I 2
J 3
K 2
L 3
M 3
N 1
P 6
R 1
S 2
U 1
V 2
W 2
X 2
Y 2
如果想按照自己的意愿排序,可以把map放進其他容器,比如vector<pair<char,int> >中,使用sort函數(shù)第三個參數(shù)來自定義排序
map<char,int> mp; vector<pair<char,int> > ans(mp.begin(),mp.end());//構(gòu)造函數(shù) sort(ans.begin(),ans.end(),cmp);//自定義排序其中cmp函數(shù):首先按照值從大到小排序;如果值相等,則按照鍵的字典序(從小到大)排序。
bool cmp(const pair<char,int> &a,const pair<char,int> &b){if(a.second==b.second) return a.first<b.first;//若相等,字典序從小到大 return a.second>b.second;//從大到小 }按值排序結(jié)果
鍵/值
P 6
A 3
D 3
J 3
L 3
M 3
B 2
F 2
G 2
H 2
I 2
K 2
S 2
V 2
W 2
X 2
Y 2
C 1
N 1
R 1
U 1
一道m(xù)ap的題目
鏈接:https://ac.nowcoder.com/acm/contest/5912/C
來源:牛客網(wǎng)
題目描述
Every problem maker has a flower in their heart out of love for ACM. As a famous problem maker, hery also has a flower.
Hery define string T as flower-string if T appears more than twice in string S and |T| = k. Hery wants you to find how many flower-string in S.
輸入描述:
The first line contains a string S consist of ’f’, ’l’, ’o’, ’w’, ’e’, ’r’ and an integer k.
(1 ≤ |S| ≤ 10^5, 1 ≤ k ≤ 100)
輸出描述:
Output an integer m in the first line, the number of flower ? string in S.
Next m lines, each line contains a flower-string and the lexicographical order of them should be from small to large
分析:長度為k的子串的個數(shù)。遍歷字符串
注意string類不要用scanf讀入。substr(i,k)函數(shù)是返回首下標是i,長度是k子串。
ac代碼
#include<iostream> #include<string> #include<algorithm> #include<map> #include<vector> using namespace std; typedef long long ll;int k; string a; map<string,int> mp;vector<string> v;int main(){cin>>a>>k;int len=a.size();for(int i=0;i+k-1<len;i++)mp[a.substr(i,k)]++;for(auto m:mp)if(m.second>2) v.push_back(m.first);sort(v.begin(),v.end());cout<<v.size()<<endl;for(auto x:v){cout<<x<<endl;}}參考博客:map按照值排序
總結(jié)
以上是生活随笔為你收集整理的C++容器map可以排序吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美国军用飞机型号由什么构成
- 下一篇: Leetcode409最长回文串 -字符