후배는 class 의 개념도 모른채.. vector 과 sort 사용법만 대충알고 구조체를 이용해서 프로그램을 짜더군요
책보기도 질리고 오랜만에 키보드질좀 해볼까 하고 손을 대어 봤네요.
백터에서 구조체를 넣을때 정렬의 기준점을 정하는 방법이 여러가지가 있더군요.
class 나 struct나 거기서 거기일테지만 C에 익숙한 저는 저게 편하더군요.
#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 ); // 점수 출력
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 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 ) // 학생 리스트 출력 이름과 총점만
{
vector::size_type i;
for( i=0 ; i