1. Day15
- C++ 문법 학습
- CH2 학습 가이드 - 12/17
2. C++ 문법 학습(Day15)
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
struct Movie {
string title;
double rating;
};
// TODO: MovieProcessor 추상 클래스 정의
// 순수 가상 함수 process를 선언해야 합니다.
// process는 vector<Movie>&를 인자로 받아야 합니다.
class MovieProcessor
{
public:
virtual void process(vector<Movie>& movies) = 0;
};
// 기본 영화 관리자
class MovieManager {
private:
vector<Movie> movies;
map<string, double> movieMap;
public:
MovieManager() {
// 초기 데이터 설정
movies = {
{"Inception", 9.0},
{"Interstellar", 8.6},
{"The Dark Knight", 9.1},
{"Memento", 8.4}
};
for (const auto& movie : movies) {
movieMap[movie.title] = movie.rating;
}
}
void printMovies() {
cout << "영화 목록:\n";
for (const auto& movie : movies) {
cout << "제목: " << movie.title << ", 평점: " << movie.rating << "\n";
}
}
void findMovie(const string& title) {
auto it = movieMap.find(title);
if (it != movieMap.end()) {
cout << "영화 제목: " << it->first << ", 평점: " << it->second << "\n";
}
else {
cout << "해당 영화는 목록에 없습니다.\n";
}
}
// MovieProcessor를 사용하여 기능 확장
void processMovies(MovieProcessor& processor) {
processor.process(movies);
}
};
// TODO: compareMovies 함수 정의
// Movies 객체의 대소를 비교하는 함수 입니다.
// STL에서 제공하는 sort 함수를 활용해서 vector<Movie>를 멤버변수 rating 기준 내림차순으로 정렬 할 수 있도록 해야 합니다.
bool compareMovies(const Movie& a, const Movie& b) {
// 내림차순 정렬
return a.rating > b.rating;
}
// TODO: RatingSorter 클래스 정의
// MovieProcessor를 상속받아 구현합니다.
// process 는 vector<Movie>&를 인자로 받으며 영화목록이 저장되어 있습니다.
// process는 인자로 받은 벡터는 내림차순으로 정렬하고, 정렬된 영화목록을 출력합니다.
class RatingSorter : public MovieProcessor {
public:
void process(vector<Movie>& movies) override
{
// 내림차순 정렬
sort(movies.begin(), movies.end(), compareMovies);
// 순서대로 출력
cout << "평점 기준 정렬된 영화 목록:" << '\n';
for (const auto& M : movies)
{
cout << "제목: " << M.title << ", 평점: " << M.rating << '\n';
}
}
};
// 구체 클래스: 특정 평점 이상의 영화 필터링
class RatingFilter : public MovieProcessor {
private:
double minRating;
public:
explicit RatingFilter(double minRating) : minRating(minRating) {}
void process(vector<Movie>& movies) {
cout << "평점 " << minRating << " 이상인 영화 목록:\n";
for (const auto& movie : movies) {
if (movie.rating >= minRating) {
cout << "제목: " << movie.title << ", 평점: " << movie.rating << "\n";
}
}
}
};
int main() {
MovieManager manager;
cout << "1. 영화 목록 출력\n";
manager.printMovies();
cout << "\n2. 영화 검색 (예: Interstellar)\n";
manager.findMovie("Interstellar");
cout << "\n3. 평점 기준 정렬 및 출력\n";
RatingSorter sorter;
manager.processMovies(sorter);
cout << "\n4. 평점 8.5 이상인 영화 필터링 및 출력\n";
RatingFilter filter(8.5);
manager.processMovies(filter);
return 0;
}
3. CH2 학습 가이드 - 12/17
// 목적: 클래스 템플릿으로 배열을 일반화하여 원소 추가 및 삭제 기능 구현하기
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class Array {
T data[100];
int size;
public:
Array() : size(0) {}
void add(const T& element) {
if (size < 100)
data[size++] = element;
}
void remove() {
if (size > 0)
size--;
}
void print() {
for (int i = 0; i < size; i++)
cout << data[i] << " ";
cout << endl;
}
// T == Array<int> arr에서 arr를 뜻 그런데 그냥 하면 복사니까 & 사용 매개변수의 int &arr 같은 느낌
// operator[] 그 뒤에 []연산자를 쓰겠다 다른 연산자 들도 사용 가능
T& operator[](int index)
{
if (index < 0 || index >= size)
{
// 여기서 예외사항이 상기면 throw해주고 main에서 try중 예외사항이 생기면 catch해서 what()으로 에러 출력
// out_of_range는 예외사항 종류
throw out_of_range("인덱스가 배열 범위를 벗어났습니다.");
}
return data[index];
}
};
int main() {
Array<int> arr; // 정수형 배열 생성
arr.add(10);
arr.add(20);
arr.add(30);
arr.print();
cout << arr[1] << '\n';
arr.remove();
try
{
cout << arr[2] << '\n';
cout << "출력 안됨" << '\n';
}
catch (const out_of_range& e)
{
cout << "예외 발생: " << e.what() << endl;
}
arr.print();
return 0;
}
// 목적: 클래스 템플릿으로 배열을 일반화하여 원소 추가 및 삭제 기능 구현하기
#include <iostream>
#include <stdexcept>
using namespace std;
template <typename T>
class Array {
T data[100];
int size;
public:
Array() : size(0) {}
void add(const T& element) {
if (size < 100)
data[size++] = element;
}
void remove() {
if (size > 0)
size--;
}
void print() {
for (int i = 0; i < size; i++)
cout << data[i] << " ";
cout << endl;
}
// T == Array<int> arr에서 arr를 뜻 그런데 그냥 하면 복사니까 & 사용 매개변수의 int &arr 같은 느낌
// operator[] 그 뒤에 []연산자를 쓰겠다 다른 연산자 들도 사용 가능
T& operator[](int index)
{
if (index < 0 || index >= size)
{
// 여기서 예외사항이 상기면 throw해주고 main에서 try중 예외사항이 생기면 catch해서 what()으로 에러 출력
// out_of_range는 예외사항 종류
throw out_of_range("인덱스가 배열 범위를 벗어났습니다.");
}
return data[index];
}
// 반복자가 없는 기본타입 배열에 반복자 추가
// 원래는 begin(기본타입 배열) 방식으로 사용해야함
T* begin() {
return data;
}
T* end() {
return data + size;
}
};
int main() {
Array<int> arr; // 정수형 배열 생성
arr.add(10);
arr.add(20);
arr.add(30);
arr.print();
cout << arr[1] << '\n';
// forech문
for (auto v : arr) {
cout << v << endl;
}
arr.remove();
try
{
cout << arr[2] << '\n';
cout << "출력 안됨" << '\n';
}
catch (const out_of_range& e)
{
cout << "예외 발생: " << e.what() << endl;
}
arr.print();
return 0;
}
4. 내일 계획 : 3, 4번 과제