코드
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
map<int, map<string, int>> students; // ID, 과목, 점수
map<string, map<int, int, greater<int>>> scores; // 과목, ID, 점수
cout << "1. 학생 성적 추가\n";
cout << "2. 학생 성적 조회\n";
cout << "3. 전체 평균 점수 출력\n";
cout << "4. 과목별 최고 점수 학생 조회\n";
cout << "5. 종료\n";
while (true)
{
cout << "메뉴 선택: ";
int choice;
cin >> choice;
// 학생 성적 추가
if (choice == 1)
{
int id, score;
string subject;
cout << "학생 ID, 과목 이름, 점수를 입력하세요: ";
cin >> id >> subject >> score;
// 0 ~ 100점까지 유효한 범위
if (score < 0 || score > 100)
continue;
students[id][subject] = score;
scores[subject][id] = score;
}
// 학생 성적 조회
else if (choice == 2)
{
int id;
cout << "학생 ID를 입력하세요: ";
cin >> id;
auto it = students.find(id);
if (it != students.end()) // 학생이 존재하면
{
cout << "학생 ID " << id << "의 성적:\n";
for (const auto& s : it->second) { // 과목 이름과 점수 출력
cout << "- " << s.first << ": " << s.second << "점\n";
}
}
else
{
cout << "존재하지 않는 학생 ID입니다.\n";
}
}
// 전체 평균 점수 출력
else if (choice == 3)
{
cout << "전체 과목 평균 점수:\n";
for (const auto& s : scores)
{
double total = 0; // 총점
double num = 0; // 학생 수
for (const auto& v : s.second)
{
total += v.second;
num++;
}
// 소수점 2번째 자리까지 출력
cout << fixed;
cout.precision(2);
cout << "- " << s.first << ": " << total/num << "점\n";
}
}
// 과목별 최고 점수 학생 조회
else if (choice == 4)
{
string name;
cout << "과목 이름을 입력하세요: ";
cin >> name;
auto it = scores.find(name);
if (it != scores.end()) // // 해당 과목의 성적이 있으면
{
// 최고 점수 계산
int maxScore = it->second.begin()->second;
cout << name << " 최고 점수: " << maxScore << "점\n";
cout << "- 학생 ID: ";
bool first = true;
for (const auto& s : it->second)
{
if (s.second == maxScore) // 최고 점수인 학생이면
{
if (!first) cout << ", ";
cout << s.first;
first = false;
}
}
cout << '\n';
}
else
{
cout << "수강한 학생이 없습니다.\n";
}
}
// 종료
else if (choice == 5) {
break;
}
else {
cout << "잘못된 메뉴 선택입니다. 다시 선택해주세요.\n";
}
}
return 0;
}
간단한 발표 자료
코드를 작성하다가 갑자기 int maxScore = it->second.begin()->second; 여기서 도트연산자(.)와 화살표연산자(->)가 헷갈려 정리했습니다.
. | 객체 | 멤버 변수나 함수를 호출할 때 사용 |
-> | 포인터 (또는 iterator) | 포인터가 가리키는 객체의 멤버에 접근할 때 사용 ((*포인터).멤버와 동일) |
'내일배움캠프 > TIL' 카테고리의 다른 글
[내일배움캠프 Day38] 8주차 과제 진행 (0) | 2025.02.12 |
---|---|
[내일배움캠프 Day37] TWeakObjectPtr (0) | 2025.02.11 |
[내일배움캠프 Day34] push_back과 emplace_back의 차이점 (1) | 2025.02.06 |
[내일배움캠프 Day32] 가상 함수 동작 원리 (0) | 2025.02.04 |
[내일배움캠프 Day31] 순차 컨테이너 (1) | 2025.02.03 |