후배가 학교에서 C++을 이용하여 성적처리 프로그램 작성 과제를 받았다는군요
그런데 교수님이 중요한 class는 안가르쳐 주시고 예제위주로만 수업을 진행하여
후배는 class 의 개념도 모른채.. vector 과 sort 사용법만 대충알고 구조체를 이용해서 프로그램을 짜더군요
책보기도 질리고 오랜만에 키보드질좀 해볼까 하고 손을 대어 봤네요.
백터에서 구조체를 넣을때 정렬의 기준점을 정하는 방법이 여러가지가 있더군요.
class 나 struct나 거기서 거기일테지만 C에 익숙한 저는 저게 편하더군요.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | #include <iostream> #include <algorithm> #include <string> #include <vector> #include <stdlib.h> using namespace std; typedef struct _student_info { string name; double mid_term; double final_term; double homework; double final_score; } st_info; int menu( void ); // 메뉴 항목 void add_student( st_info *st ); // 학생 추가 void print_vector( vector<st_info> &st ); // 점수 출력 bool compareToname( const st_info& lst, const st_info& rst ); // 이름으로 정렬 bool compareTofinal( const st_info& lst, const st_info& rst ); // 총점으로 정렬 int main( int argc, char *argv[] ) { int signal = 1; st_info st; // 백터에 추가하기 위한 임시 구조체 vector<st_info> v_st_info; // 백터 선언 while ( signal ) // 시그널을 주어서 0이면 반복 종료 { switch ( menu() ) { case 1: // 학생추가 add_student( &st ); v_st_info.push_back( st ); break ; case 2: // 학생 리스트 출력 print_vector( v_st_info ); break ; case 3: // 이름으로 정렬 sort( v_st_info.begin(), v_st_info.end(), compareToname ); break ; case 4: // 점수로 정렬 sort( v_st_info.begin(), v_st_info.end(), compareTofinal ); break ; case 5: // 종료모드 signal = 0; break ; default : // 입력이 잘못됨. 숫자제외문자 처리요망 cout << "You input Number is bad" << endl; cin.ignore(); // 작동안되는듯 break ; } // 임시 구조체 변수 초기화 st.name.clear(); st.mid_term = 0.0; st.final_term = 0.0; st.homework = 0.0; st.final_score = 0.0; } return 0; } int menu( void ) { // 메뉴 출력 및 입력 int menu; cout<< "1. add Student" << endl << "2. print" << endl << "3. des_sort" << endl << "4. asc_sort" << endl; cout<< "Input Number : " ; cin >> menu; return menu; } void add_student( st_info *st ) // 임시구조체 변수 입력 받기 { // 참조 타입이 안먹혀서 포인터타입으로 받음 cout << "Input name : " ; cin >> st->name; cout << "Input Middle test score : " ; cin >> st->mid_term; cout << "Input Final Test Score : " ; cin >> st->final_term; cout << "Input homework : " ; cin >> st->homework; st->final_score = 0.2 * st->mid_term + 0.4 * st->final_term + 0.4 * st->homework; } void print_vector( vector<st_info> &st ) // 학생 리스트 출력 이름과 총점만 { vector<st_info>::size_type i; for ( i=0 ; i<st.size() ;= "" i++)= "" {= "" cout= "" <<= "" st[i].name= "" string(10,= "" '="" ' )= "" st[i].final_score= "" endl;= "" }= "" sort= "" 함수의= "" 3번째= "" 인자= "" 이름으로= "" 오름차순정렬= "" bool = "" comparetoname(= "" const = "" st_info&= "" lst,= "" rst= "" )= "" return = "" lst.name= "" <= "" rst.name;= "" 부등호를= "" 바꾸면= "" 역순정렬= "" 총점으로= "" comparetofinal(= "" lst.final_score= "" rst.final_score;= "" }<= "" pre= "" > </st.size()></st_info></st_info></st_info></st_info> |
Posted by LaLuna