C++ 对map的value进行排序 快来打我* 2024-04-18 11:08 11阅读 0赞 #include <map> #include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; bool cmp(const pair<int, int>& a, const pair<int, int>& b) { return a.second < b.second; } int main() { int n; cin >> n; int id , score; map<int, int> mapStudent; for (int i = 0; i < n; i++) { cin >> id >> score; //插入 mapStudent.insert(pair<int, int>(id, score)); } // 将map中的内容转存到vector中 vector<pair<int, int>> vec(mapStudent.begin(), mapStudent.end()); //对线性的vector进行排序 sort(vec.begin(), vec.end(), cmp);//cmp不能少 for (int i = 0; i < vec.size(); ++i) { cout << vec[i].first << " " << vec[i].second<< endl; } } /* input: 4 1 90 2 87 3 92 4 90 output: 2 87 1 90 4 90 3 92 */
还没有评论,来说两句吧...