|
|
10장 정리문제
▶ 템플릿이 왜 필요한가?
- 함수 중복으로 작성했을 시 전체 프로그램의 길이도 늘어나고 함수를 수정하게 되면 중복된 모든 함수들의 코드를 수정해야 하는 번거로움이 생기기 때문에 매개 변수 타입만 다른 중복된 함수들을 일반화시킨 틀인 템플릿으로 작성하여 생산성과 유연성을 높일 수 있기 때문에 필요하다.
▶ 배열대신에 vector클래스를 사용하면 장점은?
- 배열은 사용자가 배열 크기를 직접정해줘야 하는 반면 vector 클래스는 배열 공간이 부족하면 스스로 더 큰 배열을 할당 받는 방식으로 내부공간을 조절하기 때문에 편리하다.
▶ STL이란 무엇인가?
- STL은 표준 템플릿 라이브러리로 템플릿으로 작성된 많은 제네릭 클래스와 함수 라이브러리이다. 컨테이너(템플릿 클래스), iterator(컨테이너 원소에 대한 포인터), 알고리즘(템플릿 함수)가 있다.
▶ STL의 컨테이너 클래스에 대하여 설명하라.
- STL의 컨테이너 클래스는 데이터를 저장하고 검색하기 위해 담아두는 자료 구조를 구현한 클래스이다. 리스트, 큐, 스택, 맵, 셋, 벡터 등이 있다.
- STL의 컨테이너 클래스는 컨테이너에 저장되는 원소를 다루는 방식에 따라 3가지 분류된다
(1) 순차 컨테이너(vector, dequeue, list 등)
- 연속적인 메모리 공간에 순서대로 값을 저장하고 있는 컨테이너
(2) 컨테이너 어뎁터(stack, queue 등)
- 다른 컨테이너를 상속받아 기능 중 일부만 공개하여 기능을 제한하거나 변형한 컨테이너
(3)연관 컨테이너(set, map 등)
- 키로 값을 저장하고 키로 검색하여 값을 알아내는 컨테이너
▶ STL의 3가지 요소 컨테이너, 이터레이터, 알고리즘의 기능을 각각 설명하라.
(1) 컨테이너
- 스스로 크기를 조절한다.
- 다양한 데이터 구조를 제공한다.
(2) 이터레이터
- 컨테이너 안에 있는 원소들을 하나씩 순차적으로 접근하여 읽기, 쓰기, 삭제 등이 가능하다.
(3) 알고리즘
- 컨테이너 원소에 대한 복사, 검색, 삭제, 정렬 등이 가능하다.
10장 문제
1번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // 10장 1번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 가장 큰 값 리턴하는 함수 template<class T> T biggest(vector<T> x, int n) { T max = x[0]; for (int i = 1; i < n; i++) { if (max < x[i]) max = x[i]; } return max; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<int> x = { 1,10,100,5,4 }; ; // int형 vector<double>y = { 1.1,2.2,3.3,4.4,5.5 }; //double형 vector<char>z = { 'a','b','c','d','e' }; //char형 // 템플릿 함수 호출 cout << biggest(x, 5) << endl; cout << biggest(y, 5) << endl; cout << biggest(z, 5) << endl; return 0; } | cs |
2번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // 10장 2번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 두 배열의 값 비교하는 함수 template<class T> bool equalArrays(vector<T>x, vector<T>y, int n) { for (int i = 0; i < n; i++) { if (x[i] != y[i]) return false; } return true; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<int>x = { 1,10,100,5,4 }; // int형 vector<int>y = { 1,10,100,5,4 }; // int형 vector<char>a = { 'a','b','c','d','e' }; //char형 vector<char>b = { 'a','b','c','d','f' }; //char형 // 템플릿 함수 호출 // int형 배열 비교 if (equalArrays(x, y, 5)) cout << "같다" << endl; else cout <<"다르다" << endl; // char형 배열 비교 if (equalArrays(a, b, 5)) cout << "같다" << endl; else cout << "다르다" << endl; return 0; } | cs |
3번
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 | // 10장 3번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 배열의 원소를 반대 순서로 뒤집는 함수 template<class T> void reverseArray(vector<T>& x, int n) { vector<T>v; for (int i = 0; i < n; i++) v.push_back(x[i]); // vector에 배열 값 저장 int index = 0; x.clear(); // 원본 vector 다 비우기 for (int i = 4; i >= 0; i--) { x.push_back(v.at(i)); // 반대로 값 저장 } } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<int>x = { 1,10,100,5,4 }; // int형 reverseArray(x, 5); for (int i = 0; i < x.size(); i++) cout << x.at(i) << ' '; return 0; } | cs |
4번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // 10장 4번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 배열에서 원소를 검색하는 함수 template<class T> bool search(T a, vector<T>x, int n) { for (int i = 0; i < n; i++) { if (x[i] == a) return true; } return false; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<int>x = { 1,10,100,5,4 }; // int형 if (search(100, x, 5)) cout << "100이 배열 x에 포함되어 있다." << endl; else cout << "100이 배열 x에 포함되어 있지 않다." << endl; return 0; } | cs |
5번
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 | // 10장 5번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 두개의 vector를 연결한 새로운 vector 반환 template<class T> vector<T> concat(vector<T>a, vector<T>b) { vector<T> v; for (int i = 0; i < a.size(); i++) v.push_back(a.at(i)); int bindex = 0; for (int i = a.size(); i < a.size() + b.size(); i++) { v.push_back(b.at(bindex)); bindex++; } return v; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 11 12 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<string>v1 = { "안녕하세요", "반갑습니다." }; vector<string>v2 = { "C++","Programming" }; vector<string>v3 = concat(v1, v2); for (int i = 0; i < v3.size(); i++) cout << v3.at(i) << ' '; return 0; } | cs |
6번
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 | // 10장 6번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 템플릿 함수 // 제네릭 타입 2개 선언 template<class T, class T2> // vector a에서 vector b에 저장된 요소 삭제한 새로운 vector 반환 vector<T> remove(vector<T>a, vector<T>b, T2& retSize) { vector<T>v; bool key; for (int i = 0; i < a.size(); i++) { key = true; for (int j = 0; j < b.size(); j++) { // a의 요소를 b 요소 하나씩 비교 if (a[i] == b[j]) { key = false; break; } } // a의 요소와 b의 요소가 같지 않을 때 vector v에 삽입 if (key) v.push_back(a[i]); } // 리턴하는 배열의 크기 반환 retSize = v.size(); return v; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //main.cpp #include "code.h" using namespace A; int main(void) { // 벡터의 다른형도 가능(double, string 등) vector<int>v1 = { 1,2,3,4,5 }; vector<int>v2 = { 2,4,6,8,10 }; int size; vector<int>v3 = remove(v1, v2, size); cout << "v3 : "; for (int i = 0; i < size; i++) cout << v3.at(i) << ' '; cout << endl << "v3에 저장된 요소의 개수 " << size << endl; return 0; } | cs |
7번
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 | // 10장 7번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // Circle 클래스 class Circle { int radius; public: Circle(int radius = 1); int getRadius(); }; // 연산자 함수 > 오버라이딩 bool operator >(Circle c1, Circle c2); // 템플릿 함수 template<class T> T bigger(T a, T b) { if (a > b) return a; else return b; } } #endif | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | // code.cpp #include "code.h" namespace A { Circle::Circle(int radius) { this->radius = radius; } // 연산자 함수 오버라이딩 bool operator >(Circle c1, Circle c2) { if (c1.getRadius() > c2.getRadius()) return true; else return false; } int Circle::getRadius() { return radius; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | //main.cpp #include "code.h" using namespace A; int main(void) { int a = 10, b = 50, c; c = bigger(a, b); cout << "20과 50중 큰 값은 " << c << endl; Circle waffle(10), pizza(20), y; y = bigger(waffle, pizza); cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl; return 0; } | cs |
- 템플릿 함수에 전달되는 자료형이 클래스일경우 클래스끼리 연산이 안되기 때문에 오류가 발생한다.
8번
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 | // 10장 8번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // Comparable 추상 클래스 class Comparable { public: // 순수 가상 함수(연산자 함수) virtual bool operator > (Comparable& op2) = 0; virtual bool operator <(Comparable& op2) = 0; virtual bool operator ==(Comparable& op2) = 0; }; // Circle 클래스 class Circle :public Comparable { int radius; public: Circle(int radius = 1); int getRadius(); bool operator > (Comparable& op2); bool operator <(Comparable& op2); bool operator ==(Comparable& op2); }; // 템플릿 함수 template<class T> T bigger(T a, T b) { if (a > b) return a; else return b; } } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { Circle::Circle(int radius) { this->radius = radius; } int Circle::getRadius() { return radius; } bool Circle::operator > (Comparable& op2) { // Comparable 타입이 Circle의 radius에 접근하기 위해 다운 캐스팅 Circle* b = (Circle*)&op2; if (this->radius > b->getRadius()) return true; else return false; } bool Circle::operator <(Comparable& op2) { // Comparable 타입이 Circle의 radius에 접근하기 위해 다운 캐스팅 Circle* b = (Circle*)&op2; if (this->radius < b->getRadius()) return true; else return false; } bool Circle::operator ==(Comparable& op2) { // Comparable 타입이 Circle의 radius에 접근하기 위해 다운 캐스팅 Circle* b = (Circle*)&op2; if (this->radius == b->getRadius()) return true; else return false; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | //main.cpp #include "code.h" using namespace A; int main(void) { int a = 10, b = 50, c; c = bigger(a, b); cout << "20과 50중 큰 값은 " << c << endl; Circle waffle(10), pizza(20), y; y = bigger(waffle, pizza); cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl; return 0; } | cs |
9번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 10장 9번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { void run(vector<int>v); } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { void run(vector<int>v) { int n; // 무한 루프 while (true) { int sum = 0; cout << "정수를 입력하세요(0을 입력하면 종료)>>"; cin >> n; if (n == 0) break; // 0 입력시 무한루프 종료 v.push_back(n); // vector 순회 하면서 요소 출력하고 총합 구하기 for (auto it = v.begin(); it != v.end(); it++) { cout << *it << ' '; sum += *it; } // 평균 출력 cout << endl << "평균 = " << (double)sum / v.size() << endl; } } } | cs |
1 2 3 4 5 6 7 8 9 | //main.cpp #include "code.h" using namespace A; int main(void) { vector<int>v; run(v); return 0; } | cs |
10번
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 | // 10장 10번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> #include<cstdlib> #include<ctime> using namespace std; namespace A { // Nation 클래스 class Nation { string nation; string captial; public: Nation(string n, string c); string getNation(); // 나라 이름 반환 string getCaptial(); // 수도 이름 반환 }; // Game 클래스 class Game { vector<Nation>v; public: Game(); void insert(); void quiz(); void run(); }; } #endif | cs |
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 91 92 93 94 95 96 97 98 99 100 101 102 103 | // code.cpp #include "code.h" namespace A { // Nation 클래스 Nation::Nation(string n, string c) { this->nation = n; this->captial = c; } string Nation::getNation() { return nation; } string Nation::getCaptial() { return captial; } // Game 클래스 // 생성자 Game::Game() { // 나라, 수도 이름 9개 초기화 v.push_back(Nation("미국", "와싱턴")); v.push_back(Nation("한국", "서울")); v.push_back(Nation("일본", "도쿄")); v.push_back(Nation("중국", "베이징")); v.push_back(Nation("독일", "베를린")); v.push_back(Nation("태국", "방콕")); v.push_back(Nation("프랑스", "파리")); v.push_back(Nation("영국", "런던")); v.push_back(Nation("호주", "시드니")); } // vector에 나라,수도 삽입하는 함수 void Game::insert() { cout << "현재 " << v.size() << "개의 나라가 입력되어 있습니다." << endl; cout << "나라와 수도를 입력하세요(no no 이면 입력끝)" << endl; string n, c; bool key; // 무한루프 while (true) { key = true; cout << (v.size() + 1) << ">>"; cin >> n >> c; // no no 입력시 무한루프 종료 if (n == "no" && c == "no") break; for (int i = 0; i < v.size(); i++) { // 이미 백터에 저장되어 있으면 if (v[i].getNation() == n) { cout << "already exists!!" << endl; key = false; //false로 변환 break; } } // key가 true일 때 if (key) { // 백터에 값 삽입 v.push_back(Nation(n, c)); } } } // 나라 이름에 대한 수도 맞추기 퀴즈 프로그램 void Game::quiz() { string s; // 무한루프 while (true) { // 랜덤 인덱스 int random = rand() % v.size(); cout << v[random].getNation() << "의 수도는?"; cin >> s; // exit 입력시 무한루프 종료 if (s == "exit") break; if (v[random].getCaptial() == s) cout << "Correct!" << endl; else cout << "No!" << endl; } } // 실행 프로그램 void Game::run() { int choose; bool key = false; cout << "***** 나라의 수도 맞추기 게임을 시작합니다. *****" << endl; // 무한루프 while (true) { cout << "정보 입력: 1, 퀴즈: 2, 종료: 3 >> "; cin >> choose; switch (choose) { case 1: insert(); //삽입 break; case 2: quiz(); //퀴즈 break; case 3: //종료 key = true; break; } if (key) break; } } } | cs |
1 2 3 4 5 6 7 8 9 | //main.cpp #include "code.h" using namespace A; int main(void) { Game game; game.run(); return 0; } | cs |
11번
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 | // 10장 11번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // Book 클래스 class Book { int year; //년도 string name; //책이름 string author; //저자 public: Book(int y, string n, string a); int getYear(); string getName(); string getAuthor(); }; // Game 클래스 class Game { vector<Book>v; public: void insert(); // 함수 중복 (저자로 검색) void Search(bool key, string s = ""); // 함수 중복 (년도로 검색) void Search(bool key, int y = 0); void run(); }; } #endif | cs |
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 91 92 | // code.cpp #include "code.h" namespace A { // Book 클래스 // 생성자 Book::Book(int y, string n, string a) { this->year = y; this->name = n; this->author = a; } int Book::getYear() { return year; } string Book::getName() { return name; } string Book::getAuthor() { return author; } // Game 클래스 // vector에 년도, 책이름, 저자 삽입하는 함수 void Game::insert() { int y; string n, a; bool key; // 무한루프 while (true) { key = true; cout << "년도>>"; cin >> y; // -1 입력시 무한루프 종료 if (y == -1) break; cin.ignore(); cout << "책이름>>"; getline(cin, n, '\n'); cout << "저자>>"; getline(cin, a, '\n'); for (int i = 0; i < v.size(); i++) { // 이미 백터에 저장되어 있으면 if (v[i].getYear() == y && v[i].getName() == n && v[i].getAuthor() == a) { cout << "이미 입고되었습니다." << endl; key = false; //false로 변환 break; } } // key가 true일 때 if (key) { // 백터에 값 삽입 v.push_back(Book(y, n, a)); } } } // 년도로 책 검색하는 함수 void Game::Search(bool key, int y) { for (int i = 0; i < v.size(); i++) { if (y == v[i].getYear()) { key = false; cout << v[i].getYear() << "년도, " << v[i].getName() << ", " << v[i].getAuthor() << endl; break; } } if (key) cout << "검색하고자 하는 책이 없습니다." << endl; } // 저자로 책 검색하는 함수 void Game::Search(bool key, string s) { for (int i = 0; i < v.size(); i++) { if (s == v[i].getAuthor()) { key = false; cout << v[i].getYear() << "년도, " << v[i].getName() << ", " << v[i].getAuthor() << endl; break; } } if (key) cout << "검색하고자 하는 책이 없습니다." << endl; } // 실행 프로그램 void Game::run() { cout << "입고할 책을 입력하세요. 년도에 -1을 입력하면 입고를 종료합니다." << endl; insert(); // 입고(삽입) cout << "총 입고된 책은 " << v.size() << "권 입니다." << endl; int y; string s; bool key; key = true; // 검색 cout << "검색하고자 하는 저자 이름을 입력하세요>>"; cin >> s; Search(key, s); cout << "검색하고자 하는 년도를 입력하세요>>"; cin >> y; Search(key, y); } } | cs |
1 2 3 4 5 6 7 8 9 | //main.cpp #include "code.h" using namespace A; int main(void) { Game game; game.run(); return 0; } | cs |
12번
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 | // 10장 12번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> #include<cstdlib> #include<ctime> using namespace std; namespace A { // Dictionary 클래스 class Dictionary { string eng; //영단어 string kor; //한글단어 public: Dictionary(string e, string k); string getEng(); string getKor(); }; // Test 클래스 class Test { vector<Dictionary>v; public: Test(); void insert(); void quiz(); void run(); }; } #endif | cs |
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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | // code.cpp #include "code.h" namespace A { // Dictionary 클래스 Dictionary::Dictionary(string e, string k) { this->eng = e; this->kor = k; } string Dictionary::getEng() { return eng; } string Dictionary::getKor() { return kor; } //Test 클래스 // 생성자 Test::Test() { v.push_back(Dictionary("honey", "애인")); v.push_back(Dictionary("apple", "사과")); v.push_back(Dictionary("banana", "바나나")); v.push_back(Dictionary("doll", "인형")); v.push_back(Dictionary("painting", "그림")); v.push_back(Dictionary("stock", "주식")); } // 백터에 삽입하는 함수 void Test::insert() { string k, e; bool key; cout << "영어 단어에 exit를 입력하면 입력 끝" << endl; while (true) { key = true; cout << "영어 >> "; cin >> e; if (e == "exit") break; cout << "한글 >> "; cin >> k; for (int i = 0; i < v.size(); i++) { // 이미 백터에 저장되어 있으면 if (v[i].getEng() == e && v[i].getKor() == k) { cout << "이미 있는 단어 입니다." << endl; key = false; //false로 변환 break; } } // key가 true일 때 if (key) { // 백터에 값 삽입 v.push_back(Dictionary(e, k)); } } } // 영단어에 대한 한글 단어 맞추는 퀴즈 프로그램 void Test::quiz() { vector<int> answer(4); // 보기 항목을 저장할 벡터, 크기를 4로 설정 int a; cout << "영어 어휘 테스트를 시작합니다. 1~4 외 다른 입력시 종료." << endl; while (true) { int Vrandom = rand() % v.size(); // 문제로 사용할 단어의 인덱스를 랜덤으로 선택 int answerRand = rand() % 4; // 정답이 들어갈 위치를 랜덤으로 선택 answer[answerRand] = Vrandom; // 정답 인덱스를 정답 위치에 배치 cout << v[Vrandom].getEng() << '?' << endl; for (int i = 0; i < 4; i++) { if (i == answerRand) continue; // 이미 정답 위치에 정답이 있으므로 건너뜀 int randV; bool key; do { key = true; randV = rand() % v.size(); // 랜덤 단어 인덱스를 선택 if (randV == Vrandom) // 문제 단어와 동일한 경우 중복 방지 { key = false; continue; } for (int j = 0; j < i; j++) // 중복된 보기 항목이 있는지 확인 { if (answer[j] == randV) { key = false; break; } } } while (!key); // 중복된 단어가 없을 때까지 반복 answer[i] = randV; // 중복되지 않는 단어를 보기 항목에 추가 } for (int i = 0; i < 4; i++) { cout << "(" << i + 1 << ") " << v[answer[i]].getKor() << ' '; } cout << " :> "; cin >> a; // 사용자 입력 받기 if (a == -1) break; // -1 입력 시 무한루프 종료 if (v[Vrandom].getKor() == v[answer[a - 1]].getKor()) cout << "Excellent!" << endl; // 정답인 경우 else cout << "No. !!" << endl; // 오답인 경우 } } // Open Challenge void Test::run() { int choose; bool key = false; srand(time(NULL)); cout << "***** 영어 어휘 테스트를 시작합니다. *****" << endl; while (true) { cout << "어휘 삽입: 1, 어휘 테스트: 2, 프로그램 종료:그외키 >> "; cin >> choose; switch (choose) { case 1: insert(); break; case 2: quiz(); break; default: key = true; break; } cout << endl; if (key) break; } } } | cs |
1 2 3 4 5 6 7 8 9 | //main.cpp #include "code.h" using namespace A; int main(void) { Test t; t.run(); return 0; } | cs |
13번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 10장 13번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<map> #include<string> using namespace std; namespace A { // Program 클래스 class Program { map<string, int>m; public: void insert(); void search(); void run(); }; } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { // 이름과 점수 map에 삽입하는 함수 void Program::insert() { string name; int grade; cout << "이름과 점수>>"; cin >> name >> grade; m.insert(make_pair(name, grade)); } // 점수 조회하는 함수 void Program::search() { string name; cout << "이름>"; cin >> name; // name에 대한 키값이 없으면 true 반환 if (m.find(name) == m.end()) cout << "없습니다" << endl; else cout << name << "의 점수는 " << m.at(name) << endl; } // 성적 관리 프로그램 void Program::run() { int choose; bool key = false; cout << "***** 점수관리 프로그램 HIGH SCORE을 시작합니다 *****" << endl; while (true) { cout << "입력:1, 조회:2, 종료:3 >> "; cin >> choose; switch (choose) { case 1: insert(); break; case 2: search(); break; case 3: key = true; break; } if (key) { cout << "프로그램을 종료합니다..." << endl; break; } } } } | cs |
1 2 3 4 5 6 7 8 9 10 | //main.cpp #include "code.h" using namespace A; int main(void) { Program p; p.run(); return 0; } | cs |
14번
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 10장 14번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<map> #include<string> using namespace std; namespace A { // Program 클래스 class Program { map<string, string>m; public: void insert(); void search(); void run(); }; } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { // 이름과 암호 map에 삽입하는 함수 void Program::insert() { string name, password; cout << "이름 암호>>"; cin >> name >> password; m.insert(make_pair(name, password)); } // 점수 조회하는 함수 void Program::search() { string name, password; cout << "이름? "; cin >> name; // name에 대한 키값이 없으면 true 반환 if (m.find(name) == m.end()) cout << "이름에 대한 정보가 없습니다" << endl; // 무한루프 while (true) { cout << "암호? "; cin >> password; // 입력한 암호와 이름에 대한 암호가 맞으면 if (password == m.at(name)) { cout << "통과!! " << endl; break; // 무한루프 종료 } else cout << "실패~~" << endl; } } // 성적 관리 프로그램 void Program::run() { int choose; bool key = false; cout << "***** 암호 관리 프로그램 WHO를 시작합니다 *****" << endl; while (true) { cout << "삽입: 1, 검사: 2, 종료: 3 >> "; cin >> choose; switch (choose) { case 1: insert(); break; case 2: search(); break; case 3: key = true; break; } if (key) { cout << "프로그램을 종료합니다..." << endl; break; } } } } | cs |
1 2 3 4 5 6 7 8 9 10 | //main.cpp #include "code.h" using namespace A; int main(void) { Program p; p.run(); return 0; } | cs |
15번
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 | // 10장 15번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // Circle 클래스 class Circle { string name; int radius; public: Circle(int radius, string name); double getArea(); string getName(); }; // Program 클래스 class Program { vector<Circle>v; public: void insert(); void Delete(); void AllData(); void run(); }; } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { //Circle 클래스 Circle::Circle(int radius, string name) { this->radius = radius; this->name = name; } double Circle::getArea() { return 3.14 * radius * radius; } string Circle::getName() { return name; } // Program 클래스 // 원 삽입하는 함수 void Program::insert() { int r; string name; cout << "생성하고자 하는 원의 반지름과 이름은 >> "; cin >> r >> name; v.push_back(Circle(r, name)); } // 원 삭제하는 함수 void Program::Delete() { string name; cout << "삭제하고자 하는 원의 이름은 >>"; cin >> name; for (auto it = v.begin(); it != v.end();) { // 이름이 같으면 삭제하기 if (it->getName() == name) it = v.erase(it); else it++; } } // vector에 저장된 모든 data 출력하는 함수 void Program::AllData() { for (int i = 0; i < v.size(); i++) { cout << v.at(i).getName() << endl; } cout << endl; } // 원 정보 프로그램 void Program::run() { int choose; bool key = false; cout << "원을 삽입하고 삭제하는 프로그램입니다." << endl; while (true) { cout << "삽입:1, 삭제:2, 모두보기:3, 종료:4 >> "; cin >> choose; switch (choose) { case 1: insert(); break; case 2: Delete(); break; case 3: AllData(); break; case 4: key = true; break; } if (key) break; } } } | cs |
1 2 3 4 5 6 7 8 9 10 | //main.cpp #include "code.h" using namespace A; int main(void) { Program p; p.run(); return 0; } | cs |
16번
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 | // 10장 16번 // code.h #ifndef CODE_H #define CODE_H #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> #include<string> using namespace std; namespace A { // 기본 클래스 class Shape { protected: virtual void draw() = 0; public: void paint(); }; // 파생 클래스 class Circle :public Shape { protected: void draw(); }; // 파생 클래스 class Rect :public Shape { protected: void draw(); }; // 파생 클래스 class Line :public Shape { protected: void draw(); }; // GraphicEditor 클래스 class GraphicEditor { vector<Shape*>v; public: void insert(); void Delete(); void AllData(); void run(); }; } #endif | cs |
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 | // code.cpp #include "code.h" namespace A { // Shape 클래스 paint 함수 void Shape::paint() { draw(); } // 파생클래스 draw 함수 오버라이딩 void Circle::draw() { cout << "Circle" << endl; } void Rect::draw() { cout << "Rectangle" << endl; } void Line::draw() { cout << "Line" << endl; } // GrahicEditor 클래스 // 도형 삽입하는 함수 void GraphicEditor::insert() { int choose; cout << "선:1, 원:2, 사각형:3 >>"; cin >> choose; switch (choose) { case 1: v.push_back(new Line()); break; case 2: v.push_back(new Circle()); break; case 3: v.push_back(new Rect()); break; } } // 도형 삭제하는 함수 void GraphicEditor::Delete() { int choose; cout << "삭제하고자 하는 도형의 인덱스 >> "; cin >> choose; auto it = v.begin(); for (int i = 0; i < choose; i++) it++; it = v.erase(it); } // 저장된 도형 모두 출력하는 함수 void GraphicEditor::AllData() { for (int i = 0; i < v.size(); i++) { cout << i << " : "; v.at(i)->paint(); } } // 도형 정보 관리하는 함수 void GraphicEditor::run() { int choose; bool key = false; cout << "그래픽 에디터입니다." << endl; while (true) { cout << "삽입:1, 삭제:2, 모두보기:3, 종료:4 >> "; cin >> choose; switch (choose) { case 1: insert(); break; case 2: Delete(); break; case 3: AllData(); break; case 4: key = true; break; } if (key) break; } } } | cs |
1 2 3 4 5 6 7 8 9 | //main.cpp #include "code.h" using namespace A; int main(void) { GraphicEditor g; g.run(); return 0; } | cs |

첫댓글 컨테이너클래스(vector 등)를 사용할때는 원소접근시 이터레이터(iterator) 객체를 이용할것 -> 배열 인덱스를 사용할 필요없음