#include <iostream>
#include <string>
#include <map>
#include <list>
using namespace std;
struct student_score {
char name[16];
int score;
};
int cmp(student_score a, student_score b)
{
return a.score > b.score;
}
int main()
{
map<string , int> ScoreMap = {
{"卢珍", 82}, {"童云", 88}, {"童贞", 71},
{"蒋成", 68}, {"姚伟", 98}, {"谢建国", 78}
}; // C++ 11X 容器方便初始化 和 auto遍历
list<student_score> ScoreList;
student_score tmp;
cout << string(30, '_') << " 建立MAP时的排序 " << string(30, '_') << endl;
for (auto it = ScoreMap.begin(); it != ScoreMap.end() ; ++it) {
cout << it->first << "\t=> " << it->second << endl;
strcpy(tmp.name, it->first.c_str());
tmp.score = it->second;
ScoreList.push_back(tmp);
}
cout << string(30, '_') << " 按成绩降序排序 " << string(30, '_') << endl;
ScoreList.sort(cmp);
for (auto it = ScoreList.begin(); it != ScoreList.end() ; ++it) {
cout << it->name << "\t=> " << it->score << endl;
}
cout << string(30, '_') << " 反转排序 " << string(30, '_') << endl;
ScoreList.reverse();
for (auto it = ScoreList.begin(); it != ScoreList.end() ; ++it) {
cout << it->name << "\t=> " << it->score << endl;
}
return 0;
}
利用unordered_map代替hash_map
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string , string> map_test;
char str[16];
int i = 0;
for (; i < 100000; i ++) {
sprintf(str, "%d", i);
map_test[str] = string(str) + "test";
}
int j = 100000;
for (; j > 0; j --) {
sprintf(str, "%d", j);
if (map_test.find(str) != map_test.end())
continue;
}
return 0;
}
// ################# unordered_map ####################################
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<string , string> um_test;
char str[16];
int i = 0;
for (; i < 100000; i ++) {
sprintf(str, "%d", i);
um_test[str] = string(str) + "test";
}
int j = 100000;
for (; j > 0; j --) {
sprintf(str, "%d", j);
if (um_test.find(str) != um_test.end())
continue;
}
return 0;
}
// ################# hash_map ####################################
#include <iostream>
#include <string>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
struct hash_string {
size_t operator()(const string& str) const {
return __stl_hash_string(str.c_str());
}
};
int main()
{
hash_map<string, string, hash_string> hm_test;
char str[16];
int i = 0;
for (; i < 100000; i ++) {
sprintf(str, "%d", i);
hm_test[str] = string(str) + "test";
}
int j = 100000;
for (; j > 0; j --) {
sprintf(str, "%d", j);
if (hm_test.find(str) != hm_test.end())
continue;
}
return 0;
}