剛剛複習了c++ map類型,參考部落格:cnblogs
1. map類型的插入和遍曆:
#include <cstdio>#include <cstring>#include <map>#include <iostream>using namespace std;int main(){ // 用insert函數插入pair資料 map<int, string> mapStudent; mapStudent.insert(pair<int, string>(1, "student_one")); mapStudent.insert(pair<int, string>(2, "student_two")); mapStudent.insert(pair<int, string>(3, "student_three")); // 用insert函數插入value_type資料 mapStudent.insert(map<int, string>::value_type(4, "student_four")); mapStudent.insert(map<int, string>::value_type(5, "student_five")); mapStudent.insert(map<int, string>::value_type(6, "student_six")); //用數組方式插入資料 mapStudent[7] = "student_seven"; mapStudent[8] = "student_eigth"; mapStudent[9] = "student_nine"; // 資料的遍曆 3種方法 // 用前向迭代器, cout<<"forward"<<endl; map<int, string>::iterator iterf; for (iterf = mapStudent.begin(); iterf != mapStudent.end(); iterf++) { cout<<iterf->first<<' '<<iterf->second<<endl; } // 還有一個反向迭代器 cout<<"backward"<<endl; map<int, string>::reverse_iterator riter; for (riter = mapStudent.rbegin(); riter != mapStudent.rend(); riter++) { cout<<riter->first<<' '<<riter->second<<endl; } //數組遍曆 cout<<"array"<<endl; int mapSize = mapStudent.size(); for (int i = 1; i <= mapSize; i++) { cout<<i<<' '<<mapStudent[i]<<endl; } return 0;}
由於不瞭解c++裡面的value_type這個知識,又查了查,但也只是瞭解一點還不太深。連結
c++ 中文手冊map的介紹:
註:find()函數返回一個迭代器指向索引值為key的元素,如果沒找到就返回指向map尾部的迭代器。
用map類型練練手,題目連結 非常簡單,就不添加註釋了
#include <cstdio>#include <iostream>#include <map>#include <cstring>using namespace std;int main(){ int n; string str; int score; while (scanf("%d", &n) != EOF) { map<string, int> student; map<string, int>::iterator ite; for (int i = 0; i < n; i++) { cin>>str>>score; ite = student.find(str); if (ite != student.end()) { if (ite->second < score) { student[str] = score; } } else student[str] = score; } for (ite = student.begin(); ite != student.end(); ite++) { cout<<ite->first<<' '<<ite->second<<endl; } } return 0;}