[PTA] 1004 成绩排序

输入格式:

第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
  ... ... ...
第 n+1 行:第 n 个学生的姓名 学号 成绩

要求输出格式:对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。

注意的点:

  1. cin>> 与 getline 函数一起使用时,输入缓冲区中换行符的问题。需要在 getline 之前使用 cin.ignore() 情况掉输入缓冲区,防止 cin>> 残留的换行符对 getline 造成影响
  2. 注意格式控制
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

int main() {
  int n;
  std::cin >> n;
  std::cin.ignore();
  std::map<int, std::vector<std::string>> item_map;
  int lowest = 100;
  int biggest = 0;
  for (int i = 0; i < n; i++) {
    std::string line;
    getline(std::cin, line);
    std::istringstream istr(line);
    std::string item;

    std::vector<std::string> v;
    while (istr >> item) {
        v.push_back(item);
        v.push_back(" ");
    }
    v.pop_back();

    auto score = atoi(v.back().c_str());
    v.pop_back();
    v.pop_back();
    item_map[score] = v;
    lowest = std::min(lowest, score);
    biggest = std::max(biggest, score);
  }

  
  for (auto v : item_map[biggest]) {   
    std::cout << v ;
  }
  std::cout << std::endl;

  for (auto v : item_map[lowest]) {
    std::cout << v ;
  }
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/hezhiqiangTS/p/12241691.html