AccCplusplus.cpp
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
usingstd::cin;
usingstd::cout;
usingstd::endl;
usingstd::setprecision;
usingstd::streamsize;
usingstd::domain_error;
usingstd::sort;
usingstd::vector;
usingstd::string;
usingstd::istream;
usingstd::max;
/* 학생데이터 구조체 */
struct Student_info
{
string name;
double midterm,final;
vector<double> homework;
};
/* 중앙값 계산 함수 */
double median(vector<double> vec)
{
typedef vector<double>::size_type vec_sz;
vec_sz size = vec.size();
/* 예외 처리 */
if(size==0)
throw domain_error("median of anempty vector");
sort(vec.begin(), vec.end());
vec_sz mid = size/2;
return (size % 2 == 0) ? (vec[mid]+vec[mid-1]) / 2 : vec[mid];
}
/* 성적 계산 함수 */
double grade(double midterm,double final,double homework)
{
return0.2 * midterm + 0.4 * final + 0.4 * homework;
}
/* 데이터 예외처리 함수 */
double grade(double midterm,double final, const vector<double>& hw)
{
if(hw.size() == 0)
throw domain_error("student has done no homework");
return grade(midterm, final, median(hw));
}
/* 학생 데이터 처리 함수 */
double grade(const Student_info& s)
{
return grade(s.midterm,s.final,s.homework);
}
/* 과제성적 저장 함수 */
istream& read_hw(istream& in,vector<double>& hw)
{
if(in)
{
hw.clear();
double x;
cout<<"homework score :";
while(in >> x)
hw.push_back(x);
in.clear();
}
return in;
}
/* 시험 성적 입력 함수 */
istream& read(istream& is,Student_info& s)
{
cout<<"name,mid,final(Exit is Ctrl+Z) : ";
is>>s.name>>s.midterm>>s.final;
read_hw(is,s.homework);
return is;
}
/* 학생이름 대소 비교 함수 */
bool compare(const Student_info& x, const Student_info& y)
{
return x.name < y.name;
}
int main()
{
vector<Student_info> students;
Student_info record;
string::size_type maxlen = 0;
while(read(cin,record))
{
// 가장 긴 이름의 길이를 얻어냄
maxlen = max(maxlen,record.name.size());
students.push_back(record);
}
// 문자열 대소 비교를 위해 직접 작성한 compare함수를 세번째 인자로 전달
sort(students.begin(), students.end(), compare);
for(vector<Student_info>::size_type i=0; i!=students.size(); ++i)
{
// 오른쪽에 maxlen+1 개의 공백문자를 포함한 이름을 출력
cout<<students[i].name
<<string(maxlen+1 - students[i].name.size(),' ');
try {
double final_grade = grade(students[i]);
streamsize prec = cout.precision();
cout<<setprecision(3)<<final_grade
<<setprecision(prec);
} catch(domain_error e) {
cout<< e.what();
}
cout<<endl;
}
return0;
}
'프로그래밍 > STL' 카테고리의 다른 글
C++,STL :: 회문(Palindromes) 예제 (0) | 2010.08.31 |
---|---|
C++,STL :: 순차 컨테이너(sequential container) 연산 (0) | 2010.08.31 |
C++,STL :: 반복자(Iterator) (0) | 2010.08.31 |
iomanip :: setw 출력 스트림의 넓이를 조절 (0) | 2010.08.29 |
iomanip :: setprecision 정밀도 계산 (0) | 2010.08.25 |
댓글 로드 중…