c++学习之STL中排序算法map
- 不能有关键字重复的元素
- 可以使用 [ ] ,下标为 关键字,返回值first和关键字相同的元素的 second
- 插入的元素可能失败(关键字重复的元素 )
简单算法
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct Student {
string name;
int score;
};
Student students[5] =
{{"Jack",77},{"Tom",64},{"xiao",99},{"Micho",89},{"Cindy",69}};
typedef map<string,int> MP;
int main(){
MP mp;
for(int i = 0;i<5;i++)
mp.insert(make_pair(students[i].name,students[i].score));
cout<< mp["Jack"] << endl;
mp["Jack"] = 60;
for(MP::iterator i =mp.begin();i != mp.end();i++)
cout << "(" <<i -> first <<"," << i->second << ")" ;
cout << endl;
Student st ;
st.name = "JK";
st.score = 99;
pair<MP::iterator,bool> p =
mp.insert(make_pair(st.name,st.score));
if( p.second ){
cout << "(" << p.first->first <<"," <<
p.first->second << ") inserted." <<endl;
}else
cout << "inserted fair !!!" << endl;
mp["Hali"] = 88 ;
MP::iterator q = mp.find("Hali");
cout << q->first <<"," << q->second <<endl;
return 0;
}
map例题:单词词频统计程序
输入大量单词, 每个单词一行不超过 20 字符,没有空格。 按出现次数 从多到少输这些单词及其出现次数。出现次数相同的,字典序靠前在前面
#include<iostream>
#include<map>
#include<set>
#include<string>
using namespace std;
struct Word{
int times;
string wd;
};
struct Rule{
bool operator()(const Word &w1 , const Word &w2){
if (w1.times != w2.times)
return w1.times > w2.times;
else
return w1.wd < w2.wd;
}
};
int main(){
string s;
set<Word,Rule> st;
map<string,int> mp;
int t ;
cout << "input times:";
cin >> t;
while(t){
cin >> s;
++ mp[s];
t--;
}
for (map<string,int>::iterator i = mp.begin();
i!= mp.end();i++){
Word tmp;
tmp.wd = i->first;
tmp.times = i->second;
st.insert(tmp);
}
for(set<Word,Rule>::iterator i = st.begin();
i!=st.end();i++)
cout << i ->wd << " " << i->times << endl;
return 0;
}